Objective-C 中存储到钥匙串的值无法在 Swift 中检索?
Value stored to Keychain in Objective-C can't be retrieved in Swift?
我在钥匙串方面遇到了最奇怪的问题。我有一个现有的应用程序正在使用加密的 Realm 数据库,并且根据 Realm 的代码示例 here.
,加密密钥被保存到钥匙串中
- (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[= 检索存储在钥匙串中的加密密钥18=]
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:
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer([=13=])) }
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 代码无法 return Objective-C 代码存储在钥匙串中的值。我尝试修改 Swift 代码以在创建 keychainIdentifierData 时使用 NSData 而不是数据,但我就是无法让它工作。
在我的实际项目中,SecItemCopyMatching 调用return是成功状态,但dataTypeRef 始终为nil,在强制转换为Data 时崩溃。在我为此创建的一个小测试项目中,找不到密钥,这似乎表明问题在于将 keychainIdentifier 转换为 keychainIdentifierData,但我现在找不到任何信息如何在不同语言之间一致地执行此操作。
我发现的一个线索是将 tag/keychainIdentifierData 打印到控制台,在 Obj-c 中是
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 7900>
在 Swift 中是
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 79>
这表明密钥在语言之间不匹配,但我不明白为什么 SecItemCopyMatching return 成功。
有人知道如何取回我的加密密钥吗?提前致谢:)
Objective-C keychainIdentifier
被创建为 C 字符串,它始终以 null 结尾。空终止符与导致您注意到的尾随“00”附加到结果的字符一起编码。 Swift 字符串不是空终止的。
为了实现奇偶校验,在创建 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];
根据 ncke 的 answer/comment 创建一个答案:
密钥在我的 Swift keychainIdentifierData 的末尾附加了一个空终止符,就像这样
keychainIdentifierData.append(0)
我在钥匙串方面遇到了最奇怪的问题。我有一个现有的应用程序正在使用加密的 Realm 数据库,并且根据 Realm 的代码示例 here.
,加密密钥被保存到钥匙串中- (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[= 检索存储在钥匙串中的加密密钥18=]
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:
var dataTypeRef: AnyObject?
var status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer([=13=])) }
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 代码无法 return Objective-C 代码存储在钥匙串中的值。我尝试修改 Swift 代码以在创建 keychainIdentifierData 时使用 NSData 而不是数据,但我就是无法让它工作。
在我的实际项目中,SecItemCopyMatching 调用return是成功状态,但dataTypeRef 始终为nil,在强制转换为Data 时崩溃。在我为此创建的一个小测试项目中,找不到密钥,这似乎表明问题在于将 keychainIdentifier 转换为 keychainIdentifierData,但我现在找不到任何信息如何在不同语言之间一致地执行此操作。
我发现的一个线索是将 tag/keychainIdentifierData 打印到控制台,在 Obj-c 中是
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 7900>
在 Swift 中是
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 79>
这表明密钥在语言之间不匹配,但我不明白为什么 SecItemCopyMatching return 成功。
有人知道如何取回我的加密密钥吗?提前致谢:)
Objective-C keychainIdentifier
被创建为 C 字符串,它始终以 null 结尾。空终止符与导致您注意到的尾随“00”附加到结果的字符一起编码。 Swift 字符串不是空终止的。
为了实现奇偶校验,在创建 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];
根据 ncke 的 answer/comment 创建一个答案:
密钥在我的 Swift keychainIdentifierData 的末尾附加了一个空终止符,就像这样
keychainIdentifierData.append(0)