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

iAm*_*Amd 1 encryption realm ios swift

我试图加密存储在领域数据库中的数据.我按照Realm的Swift页面上提到的示例代码.我想加密数据而不是数据库文件.以下是我正在使用的代码:

    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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

对象是我需要在数据库中插入的对象列表.下面是从示例代码中挑选的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
}
Run Code Online (Sandbox Code Playgroud)

问题是代码没有加密.在我使用Realm Browser打开领域文件时插入数据后,代码未加密.

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

有任何想法吗?

TiM*_*TiM 6

Realm的加密功能仅适用于加密整个.realm文件的能力.没有功能可以加密.realm文件中的离散对象,并保持其余部分不变.

如果您确实想要这样做,我担心您需要自己滚动加密系统.

如果我打算这样做,我会这样做:

  1. Object使用NSData名为的属性 创建Realm 子类encryptedData.
  2. NSData使用NSCoding协议序列化您要加密的任何对象.(使用NSCoding将自定义SWIFT类保存到UserDefaults)
  3. NSData使用您选择的加密方法加密生成的对象(iPhone上的NSString的AES加密)
  4. 获取生成的加密NSData对象并将其保存到encryptedDataRealm对象中的属性.
  5. 要检索该数据时,请反转该过程.

虽然这个过程可行,但正如您所看到的,这是一项非常重要的额外工作,您也将失去Realm在此过程中的所有速度和内存节省优势.

我鼓励你重新考虑你的应用程序的设计,看看毕竟使用Realm自己的加密功能是否可行.祝好运!