SWIFT - Realm db加密无法正常工作

时间:2015-09-22 13:19:37

标签: ios swift encryption realm

我试图加密存储在领域数据库中的数据。我遵循了Realm Sample Code中提到的Swift page。我想加密数据而不是数据库文件。以下是我正在使用的代码:

    var error: NSError? = nil
    let configuration = Realm.Configuration(encryptionKey: EncryptionManager().getKey())

    if let realmE = Realm(configuration: configuration, error: &error) {
        // Add an object
        realmE.write {
            realmE.add(objects, update: T.primaryKey() != nil)
        }
    }

其中objects是我需要在数据库中插入的对象列表。下面是从示例代码中选择的getKey()函数前面的代码:

func getKey() -> NSData {
    // Identifier for our keychain entry - should be unique for your application
    let keychainIdentifier = "io.Realm.test"
    let keychainIdentifierData = keychainIdentifier.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

    // First check in the keychain for an existing key
    var query: [NSString: AnyObject] = [
        kSecClass: kSecClassKey,
        kSecAttrApplicationTag: keychainIdentifierData,
        kSecAttrKeySizeInBits: 512,
        kSecReturnData: true
    ]

    // To avoid Swift optimization bug, should use withUnsafeMutablePointer() function to retrieve the keychain item
    // See also: http://stackoverflow.com/questions/24145838/querying-ios-keychain-using-swift/27721328#27721328
    var dataTypeRef: AnyObject?
    var status = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) }
    if status == errSecSuccess {
        return dataTypeRef as! NSData
    }

    // No pre-existing key from this application, so generate a new one
    let keyData = NSMutableData(length: 64)!
    let result = SecRandomCopyBytes(kSecRandomDefault, 64, UnsafeMutablePointer<UInt8>(keyData.mutableBytes))

    // Store the key in the keychain
    query = [
        kSecClass: kSecClassKey,
        kSecAttrApplicationTag: keychainIdentifierData,
        kSecAttrKeySizeInBits: 512,
        kSecValueData: keyData
    ]

    status = SecItemAdd(query, nil)
    assert(status == errSecSuccess, "Failed to insert the new key in the keychain")

    return keyData
}

问题在于代码未加密。在使用Realm Browser打开域文件时插入数据后,代码未加密。

在模拟器和设备上进行测试。使用Swift 1.2,Xcode 6.4,Realm 0.95。

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

Realm的加密功能仅适用于加密整个.realm文件的功能。没有任何功能可以加密.realm文件中的离散对象,并将其余部分保留原样。

如果您确实想要这样做,我担心您需要自己推出加密系统。

如果我要这样做,我就是这样做的:

  1. 创建一个名为Object的子类,其中包含NSData属性 encryptedData
  2. 使用以下命令将要加密的任何对象序列化为NSData NSCoding协议。 (Saving custom SWIFT class with NSCoding to UserDefaults
  3. 使用您选择的加密方法(AES Encryption for an NSString on the iPhone
  4. 加密生成的NSData对象
  5. 获取生成的加密NSData对象,并将其保存到Realm对象中的encryptedData属性。
  6. 如果要检索该数据,请反转该过程。
  7. 虽然这个过程可行,但正如您所看到的,它是一项非常重要的额外工作,您还将失去Realm在此过程中的所有速度和内存节省优势。

    我建议您重新考虑应用程序的设计,看看是否可以使用Realm自己的加密功能。祝你好运!

相关问题