热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

存储在Objective-C中的Keychain的值无法在Swift中检索?

如何解决《存储在Objective-C中的Keychain的值无法在Swift中检索?》经验,为你挑选了1个好方法。

我遇到了钥匙扣最棘手的问题.我有一个现有的应用程序,它是使用加密的境界数据库,加密密钥被保存到钥匙扣,按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代码示例存储在Keychain加密密钥在这里

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代码返回存储在Keychain中的值.我在创建keychainIdentifierData时尝试修改Swift代码以使用NSData而不是Data,但我无法让它工作.

在我的实际项目中,SecItemCopyMatching调用返回成功状态,但dataTypeRef始终为nil,在强制转换为Data时崩溃.在我为此创建的一个小测试项目中,找不到密钥,这似乎表明问题在于将keychainIdentifier转换为keychainIdentifierData,但我现在找不到任何信息如何在语言之间保持一致.

我发现的一个线索是将标签/ keychainIdentifierData打印到控制台,在Obj-c中它是 <696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 7900>
Swift中的位置
<696f2e52 65616c6d 2e456e63 72797074 696f6e45 78616d70 6c654b65 79>

这表明密钥在语言之间不匹配,但后来我不明白为什么SecItemCopyMatching会返回成功.

有没有人对如何检索我的加密密钥有任何见解?提前致谢 :)



1> ncke..:

Objective-C keychainIdentifier被创建为C字符串,它始终以null结尾.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];


推荐阅读
author-avatar
沈婧颖_491
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有