简体   繁体   中英

SecKeyRef to base64 and back in swift

I am trying to generate a public/private pair of keys on the device and store them in the keychain.

Since i am using swift i will use a library to interact with the keychain. This is the one i found for that https://github.com/matthewpalmer/Locksmith .

What i need to do after i generate the keys is to convert them both in base64 and then store them in the key chain and afterwards recreate both keys using the base64 string from the keychain.

Using the Locksmith library this should be something like this.

Locksmith.saveData(["publicKeyKey": "publicKeyBase64data"], forUserAccount: "myUserAccount")

To generate the keys i use the following code

public func GenerateKeys() -> [SecKeyRef]{

    let keySize = 2048;
    var publicKeyPtr, privateKeyPtr: Unmanaged<SecKeyRef>?

    let publicKeyParameters: [String: AnyObject] = [
        kSecAttrIsPermanent as String: true,
        kSecAttrApplicationTag as String: "com.site.key.public"
    ]

    let privateKeyParameters: [String: AnyObject] = [
        kSecAttrIsPermanent as String: true,
        kSecAttrApplicationTag as String: "com.site.key.private"
    ]

    let parameters: [String: AnyObject] = [
        kSecAttrKeyType as! String: kSecAttrKeyTypeRSA,
        kSecAttrKeySizeInBits as! String: keySize,
        kSecPublicKeyAttrs.takeUnretainedValue() as! String: publicKeyParameters,
        kSecPrivateKeyAttrs.takeUnretainedValue() as! String: privateKeyParameters
    ]

    let result = SecKeyGeneratePair(parameters, &publicKeyPtr, &privateKeyPtr)
    let publicKey = publicKeyPtr!.takeRetainedValue()
    let privateKey = privateKeyPtr!.takeRetainedValue()
    let blockSize = SecKeyGetBlockSize(publicKey)

    return [publicKey, privateKey];
}

I am able to generate the keys successfully but i can't figure out how to convert them to base64 and back. So i have the SecKeyRef objects but don't really know to continue.

Most of the code i have found already is in objective-c which i am not so familiar with.

Any kind of help is appreciated.

Thanks

You don't really need another keychain provider. You have set the kSecAttrIsPermanent parameter to true, so according to Apple doc the keyPair is already stored in default keychain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM