如何在Swift中检查密钥是否存储在KeyChain中

时间:2019-05-29 08:38:43

标签: ios swift keychain

我试图在KeyChain中存储两个私钥和公钥,当我尝试这样做时,我的结果有价值的返回值0(我认为这意味着它已经存储了),但是当我尝试返回解密消息时,我是返回为零,所以是否有办法检查密钥是否基于存储SecItemCopyMatching?但创建它们时我没有任何错误

let tagName = "PrivateKeyTag"
let privkey = "key"
        let privkeyData = Data(privkey!.utf8)
        let privateFilter: [String : Any] = [
            (kSecClass as String)              : kSecClassKey,
            (kSecAttrKeyType as String)        : kSecAttrKeyTypeRSA,
            (kSecAttrApplicationTag as String) : tagName,
            (kSecValueData as String)          : privkeyData,
            (kSecAttrKeyClass as String)       : kSecAttrKeyClassPrivate,
           // kSecAttrKeySizeInBits as String: 2048,
            (kSecReturnPersistentRef as String): true,

            ] as [String : Any]
        let result = SecItemAdd(privateFilter as CFDictionary, nil)
        if ((result != noErr) && (result != errSecDuplicateItem)) {
            NSLog("Cannot add key to keychain, status \(result).")
        }

let getquery: [String: Any] = [kSecClass as String: kSecClassKey,
                                       kSecAttrApplicationTag as String: tag,
                                       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                                       ]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(getquery as CFDictionary, &item)
        guard status == errSecSuccess else {
            print("key not found")
            return
        }
        let key = item as! SecKey

1 个答案:

答案 0 :(得分:0)

创建加密密钥时,可以将参数kSecAttrIsPermanent设置为true,它将自动将密钥存储在默认密钥链中。这将清除您的代码,因此您不再需要处理SecItemAdd()以及与此相关的所有错误处理。因此,这是一种更简单的方法来做您想做的事情。

要创建密钥并查询密钥

let tag = "com.example.keys.mykey".data(using: .utf8)!
let attributes: [String: Any] =
    [kSecAttrKeyType as String:            kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits as String:      2048,
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    true,
         kSecAttrApplicationTag as String: tag]
]

let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, nil) 
let query: [String: Any] = [kSecClass as String: kSecClassKey,
                            kSecAttrApplicationTag as String: tag,
                            kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
                            kSecReturnRef as String: true]
var item: CFTypeRef?
let status2 = SecItemCopyMatching(query as CFDictionary, &item)
guard status2 == errSecSuccess else { print("error1"); return }
let key = item as! SecKey

运行此代码,我相信它将完成您在问题中提供的代码中想要做的事情。我试过运行您提供的代码,而我正在使用的Xcode和Swift版本会导致编译器错误。

如果您在此答案中运行代码,您会注意到没有错误打印到控制台,表明在默认钥匙串中成功找到了钥匙。