Skip to content

Commit 85881c9

Browse files
committed
Check SQLCipher database integrity on key()
Fixes stephencelis#144. Signed-off-by: Stephen Celis <stephen@stephencelis.com>
1 parent 0913f5d commit 85881c9

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

Source/Cipher/Cipher.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ extension Connection {
2626

2727
public func key(key: String) throws {
2828
try check(sqlite3_key(handle, key, Int32(key.utf8.count)))
29+
try execute(
30+
"CREATE TABLE \"__SQLCipher.swift__\" (\"cipher key check\");\n" +
31+
"DROP TABLE \"__SQLCipher.swift__\";"
32+
)
2933
}
3034

3135
public func rekey(key: String) throws {

Tests/CipherTests.swift

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,34 @@ class CipherTests: XCTestCase {
1515
}
1616

1717
func test_key() {
18-
XCTAssertEqual(1, try! db.scalar("SELECT count(*) FROM foo") as! Int64)
18+
XCTAssertEqual(1, db.scalar("SELECT count(*) FROM foo") as? Int64)
1919
}
2020

2121
func test_rekey() {
2222
try! db.rekey("goodbye")
23-
XCTAssertEqual(1, try! db.scalar("SELECT count(*) FROM foo") as! Int64)
23+
XCTAssertEqual(1, db.scalar("SELECT count(*) FROM foo") as? Int64)
24+
}
25+
26+
func test_keyFailure() {
27+
let path = "\(NSTemporaryDirectory())/db.sqlite3"
28+
_ = try? NSFileManager.defaultManager().removeItemAtPath(path)
29+
30+
let connA = try! Connection(path)
31+
defer { try! NSFileManager.defaultManager().removeItemAtPath(path) }
32+
33+
try! connA.key("hello")
34+
35+
let connB = try! Connection(path)
36+
37+
var rc: Int32?
38+
do {
39+
try connB.key("world")
40+
} catch Result.Error(_, let code, _) {
41+
rc = code
42+
} catch {
43+
XCTFail()
44+
}
45+
XCTAssertEqual(SQLITE_NOTADB, rc)
2446
}
2547

2648
}

0 commit comments

Comments
 (0)