简体   繁体   English

SecKeyRef到base64并快速返回

[英]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. 由于我使用的是Swift,因此我将使用一个库与钥匙串进行交互。 This is the one i found for that https://github.com/matthewpalmer/Locksmith . 这是我为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. 生成密钥后,我需要做的是将它们都转换为base64,然后将它们存储在密钥链中,然后使用来自密钥链的base64字符串重新创建两个密钥。

Using the Locksmith library this should be something like this. 使用Locksmith库应该是这样的。

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. 我能够成功生成密钥,但是我不知道如何将它们转换为base64并返回。 So i have the SecKeyRef objects but don't really know to continue. 所以我有SecKeyRef对象,但真的不知道要继续。

Most of the code i have found already is in objective-c which i am not so familiar with. 我发现的大多数代码都在我不太熟悉的Objective-C中。

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. 您已将kSecAttrIsPermanent参数设置为true,因此根据Apple doc,keyPair已存储在默认钥匙串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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