将SecKey存储到钥匙串中/从钥匙串中检索

时间:2019-09-02 13:42:24

标签: swift security seckeyref

我有一个私人SecKey,需要保存在我的钥匙串中。到目前为止,没有错误,但是如果我将写的哈希值与读回的哈希值进行比较,就会有所不同。

var loginPrivateKey: SecKey?{
    get{
        let query: [String: Any] = [
            String(kSecClass)             : kSecClassKey,
            String(kSecAttrKeyType)       : kSecAttrKeyTypeEC,
            String(kSecReturnRef)         : true as Any
        ]

        var result : AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)

        if status == errSecSuccess {
            return result as! SecKey?
        }
        return nil
    }
    set{
        if let value = newValue{
            let attribute = [
                String(kSecClass)              : kSecClassKey,
                String(kSecAttrKeyType)        : kSecAttrKeyTypeEC,
                String(kSecValueRef)           : value,
                String(kSecReturnPersistentRef): true
                ] as [String : Any]

            let status = SecItemAdd(attribute as CFDictionary, nil)

            if status != noErr {
                print("SecItemAdd Error!")
                return
            }
        }
        else{
            deleteAllSecKeys()
        }
    }
}


func deleteAllSecKeys(){
    let query : [String: AnyObject] = [
        String(kSecClass)             : kSecClassKey
    ]
    let status = SecItemDelete(query as CFDictionary)

    switch status {
    case errSecItemNotFound:
        print("No key in keychain")
    case noErr:
        print("All Keys Deleted!")
    default:
        print("SecItemDelete error! \(status.description)")
    }
}

这里是测试:

func testLoginPrivateKey(){

        let helper = KeychainHelper()
        let oldKey = helper.loginPrivateKey
        let key = LoginModel().createJWK()?.privateKey
        helper.loginPrivateKey = key
        XCTAssertTrue(helper.loginPrivateKey.hashValue == key.hashValue)
        helper.loginPrivateKey = oldKey
    }

0 个答案:

没有答案