2
我想使用預先填充數據的加密的Realm數據庫。問題是我在本地生成密鑰並將其存儲在設備上,並且您可以想像,密鑰在我將該領域文件帶到其他設備的那一刻不起作用。這是我如何生成加密密鑰。是否可以在不明確聲明密鑰的情況下使用預填充的加密領域文件?
func getKey() -> NSData {
// Identifier for our keychain entry - should be unique for your application
let keychainIdentifier = "io.Realm.Test12345"
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)!
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
}
有沒有什麼辦法可以做到這一點,而沒有明確指出可以在所有設備上打開文件的密鑰?我想我可以在代碼中逐行生成數據庫,並確保它從一開始就被加密,但它並不方便。
你最終只是在應用程序中存儲加密密鑰? – SimplyLearning
@SimplyLearning結束了我剛剛使用我的服務器查詢結果,使用速率限制,以便不是所有的結果都可以輕鬆獲取。這是我用例中的工作。 – AppreciateIt
啊,所以你最終只是和你的服務器一起去完全離線Realm?我利用Realm並希望在應用程序下載時加密我的數據庫,所以想到的只是在幫助文件中對關鍵字進行硬編碼 – SimplyLearning