我在使用钥匙串时遇到了最奇怪的问题。根据Realm的代码示例here,我有一个现有的应用程序正在使用加密的Realm数据库,并且加密密钥正在保存到钥匙串中。
- (NSData *)getKey {
// Identifier for our keychain entry - should be unique for your application
static const uint8_t kKeychainIdentifier[] = "io.Realm.EncryptionExampleKey";
NSData *tag = [[NSData alloc] initWithBytesNoCopy:(void *)kKeychainIdentifier
length:sizeof(kKeychainIdentifier)
freeWhenDone:NO];
// First check in the keychain for an existing key
NSDictionary *query = @{(__bridge id)kSecClass: (__bridge id)kSecClassKey,
(__bridge id)kSecAttrApplicationTag: tag,
(__bridge id)kSecAttrKeySizeInBits: @512,
(__bridge id)kSecReturnData: @YES};
CFTypeRef dataRef = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataRef);
if (status == errSecSuccess) {
return (__bridge NSData *)dataRef;
}
// No pre-existing key from this application, so generate a new one
uint8_t buffer[64];
status = SecRandomCopyBytes(kSecRandomDefault, 64, buffer);
NSAssert(status == 0, @"Failed to generate random bytes for key");
NSData *keyData = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
// Store the key in the keychain
query = @{(__bridge id)kSecClass: (__bridge id)kSecClassKey,
(__bridge id)kSecAttrApplicationTag: tag,
(__bridge id)kSecAttrKeySizeInBits: @512,
(__bridge id)kSecValueData: keyData};
status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
NSAssert(status == errSecSuccess, @"Failed to insert new key in the keychain");
return keyData;
}
我正在将该应用程序转换为Swift,并且我正在尝试使用Realm的swift代码示例here
来检索存储在钥匙串中的加密密钥。func getKey() -> NSData {
// Identifier for our keychain entry - should be unique for your application
let keychainIdentifier = "io.Realm.EncryptionExampleKey"
let keychainIdentifierData = keychainIdentifier.data(using: String.Encoding.utf8, allowLossyConversion: false)!
// First check in the keychain for an existing key
var query: [NSString: AnyObject] = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecReturnData: true as AnyObject
]
// 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(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, 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, keyData.mutableBytes.bindMemory(to: UInt8.self, capacity: 64))
assert(result == 0, "Failed to get random bytes")
// Store the key in the keychain
query = [
kSecClass: kSecClassKey,
kSecAttrApplicationTag: keychainIdentifierData as AnyObject,
kSecAttrKeySizeInBits: 512 as AnyObject,
kSecValueData: keyData
]
status = SecItemAdd(query as CFDictionary, nil)
assert(status == errSecSuccess, "Failed to insert the new key in the keychain")
return keyData
}
现在的问题是,Swift代码无法返回由Objective-C代码存储在钥匙串中的值。在创建keychainIdentifierData时,我曾尝试将Swift代码修改为使用NSData而不是Data,但是我无法使其正常工作。
在我的实际项目中,SecItemCopyMatching调用返回成功状态,但是dataTypeRef始终为nil,这在施于Data时强制崩溃。在为此创建的一个小型测试项目中,未找到密钥,这似乎表明问题出在将keychainIdentifier转换为keychainIdentifierData,但我现在找不到任何信息如何在不同语言之间保持一致。 / p>
我发现的一个提示是将tag / keychainIdentifierData打印到控制台,在Obj-c中是
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 7900>
在Swift中哪里
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 79>
哪个表示各语言的键不匹配,但是我不明白为什么SecItemCopyMatching返回成功。
有人对如何检索我的加密密钥有任何见识吗?在此先感谢:)
答案 0 :(得分:5)
正在将Objective-C keychainIdentifier
创建为C字符串,这些字符串始终以null终止。空终止符与会导致尾随的“ 00”的字符一起编码,并附加到结果中。 Swift字符串不以null终止。
要实现奇偶校验,请在创建Objective-C标识符时省略最后一个字符:
static const uint8_t kKeychainIdentifier[] = "io.Realm.EncryptionExampleKey";
NSData *tag = [[NSData alloc] initWithBytesNoCopy:(void *)kKeychainIdentifier
length:sizeof(kKeychainIdentifier) - 1 // <- Truncate last char
freeWhenDone:NO];
或者,使用NSString在Objective-C中表示您的标识符:
NSString *keychainIdentifier = @"io.Realm.EncryptionExampleKey";
NSData *tag = [keychainIdentifier dataUsingEncoding:NSUTF8StringEncoding];
答案 1 :(得分:0)
根据ncke的答案/评论创建答案
关键是像这样在我的Swift keychainIdentifierData的末尾添加了一个空终止符
keychainIdentifierData.append(0)