|
| 1 | +# PowerSync encryption demo |
| 2 | + |
| 3 | +A tiny app opening an encrypted database with PowerSync. |
| 4 | + |
| 5 | +This example only opens a local database and does not setup a sync client. |
| 6 | +Since encryption happens at a low level using SQLite3 Multiple Ciphers, all regular PowerSync APIs are available |
| 7 | +for encrypted databases too. |
| 8 | + |
| 9 | +## Setup |
| 10 | + |
| 11 | +PowerSync has no builtin encryption primitives, but can be made to work with [SQLite3 Multiple Ciphers](https://utelle.github.io/SQLite3MultipleCiphers/) (`sqlite3mc`). |
| 12 | +By using the `initialStatements` parameter when opening databases, you can run `PRAGMA key` statements to configure |
| 13 | +encryption. |
| 14 | + |
| 15 | +To use `sqlite3mc` instead of regular `sqlite3`, note that PowerSync depends on [this project](github.com/powersync-ja/CSQLite) to compile and link SQLite into your app. |
| 16 | +To support encryption, enable the `Encryption` trait for that package. Since XCode doesn't support package traits, the |
| 17 | +workaround is to create a SwiftPM project in your XCode project (called `helper/` in this demo). |
| 18 | +In `helper/Package.swift`, depend on CSQLite with the `Encryption` trait: |
| 19 | + |
| 20 | +```Swift |
| 21 | +// swift-tools-version: 6.2 |
| 22 | +import PackageDescription |
| 23 | + |
| 24 | +let package = Package( |
| 25 | + name: "helper", |
| 26 | + products: [ |
| 27 | + // Products define the executables and libraries a package produces, making them visible to other packages. |
| 28 | + .library( |
| 29 | + name: "helper", |
| 30 | + targets: ["helper"] |
| 31 | + ), |
| 32 | + ], |
| 33 | + dependencies: [ |
| 34 | + .package(url: "https://github.com/powersync-ja/CSQLite.git", exact: "3.51.2", traits: ["Encryption"]), |
| 35 | + ], |
| 36 | + targets: [ |
| 37 | + .target( |
| 38 | + name: "helper", |
| 39 | + dependencies: [.product(name: "CSQLite", package: "CSQLite")] |
| 40 | + ), |
| 41 | + ] |
| 42 | +) |
| 43 | +``` |
| 44 | + |
| 45 | +Note that `Sources/helper/helper.swift` can be an empty file, but it needs to exist for this to compile. |
| 46 | + |
| 47 | +Next, add a dependency to this local project from XCode and resolve packages. This will enable your entire app, including |
| 48 | +the PowerSync framework, to use `sqlite3mc`. |
| 49 | + |
| 50 | +Finally, add `initialStatements` to encrypt databases: |
| 51 | + |
| 52 | +```Swift |
| 53 | +let ps = PowerSyncDatabase( |
| 54 | + schema: yourSchema, |
| 55 | + initialStatements: ["pragma key = 'TODO: your key'"] |
| 56 | +) |
| 57 | +``` |
0 commit comments