How do I export a public key that was generated using SecKeyGeneratePair to be used on a server?

前端 未结 1 1439
一向
一向 2021-02-06 19:14

I generated a keeper using SecKeyGeneratePair.

        var publicKeyPtr, privateKeyPtr: Unmanaged?

        let publicKeyParameters: [String: AnyO         


        
相关标签:
1条回答
  • SecItemCopyMatching is for you:

    var dataPtr:Unmanaged<AnyObject>?
    let query: [String:AnyObject] = [
        kSecClass: kSecClassKey,
        kSecAttrApplicationTag: "com.example.site.public",
        kSecReturnData: kCFBooleanTrue
    ]
    let qResult = SecItemCopyMatching(query, &dataPtr)
    
    // error handling with `qResult` ...
    
    let publicKeyData = dataPtr!.takeRetainedValue() as NSData
    
    // convert to Base64 string
    let base64PublicKey = publicKeyData.base64EncodedStringWithOptions(nil)
    

    Swift 4:

    var dataPtr:CFTypeRef?
    let query: [String: Any] = [
        kSecClass as String: kSecClassKey,
        kSecAttrApplicationTag as String: "com.example.site.public",
        kSecReturnData as String: true
    ]
    
    let qResult = SecItemCopyMatching(query as CFDictionary, &dataPtr)
    
    // error handling with `qResult` ...
    
    let data = dataPtr as! Data
    let base64PublicKey = data.base64EncodedString()
    

    Note that the size of the data is 270, not the same as block size of the key. See this question on the crypto.stackexchange.com.

    0 讨论(0)
提交回复
热议问题