Swift 3将SecKey导出到String [英] Swift 3 export SecKey to String

查看:381
本文介绍了Swift 3将SecKey导出到String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift 3开发iOS应用.

I am developing an iOS app using swift 3.

我需要将SecKey(这是用户RSA公钥引用)导出到字符串(例如base64),以便通过生成的QRCode共享它.

I need to export an SecKey (which is the user RSA publickey reference) to a string (e.g base64) in order to share it through a generated QRCode.

它还必须以其他方式工作,因为其他扫描QRCode的用户将能够从QRCode提取的字符串中重建SecKey引用.

It also has to work the other way since the other user that scans the QRCode, will be able to rebuild a SecKey reference from the string extracted from the QRCode.

我发现很少有教程,但是我不完全了解我需要从SecKey参考中提取什么,而且我也不知道如何将其转换为String.

I found few tutorials but I don't understand exactly what I need to extract from the SecKey reference, and I don't know how to convert it to a String.

推荐答案

导出密钥(仅适用于iOS 10)

var error:Unmanaged<CFError>?
if let cfdata = SecKeyCopyExternalRepresentation(publicKey!, &error) {
   let data:Data = cfdata as Data
   let b64Key = data.base64EncodedString()
}

请参见 https://stackoverflow.com/a/30662270/5276890 https://stackoverflow.com/a/27935528/5276890 以获得可能支持iOS的更长方式< 10.

See https://stackoverflow.com/a/30662270/5276890 and https://stackoverflow.com/a/27935528/5276890 for longer ways which probably support iOS < 10.

重新导入密钥

guard let data2 = Data.init(base64Encoded: b64Key) else {
   return
}

let keyDict:[NSObject:NSObject] = [
   kSecAttrKeyType: kSecAttrKeyTypeRSA,
   kSecAttrKeyClass: kSecAttrKeyClassPublic,
   kSecAttrKeySizeInBits: NSNumber(value: 512),
   kSecReturnPersistentRef: true as NSObject
]

guard let publicKey = SecKeyCreateWithData(data2 as CFData, keyDict as CFDictionary, nil) else {
    return
}

注意:这将生成base64密钥,而不是证书.在线上的许多代码示例都涉及如何使用SecCertificateCreateWithData从证书生成公钥

Note: This generates a base64 key and not a certificate. A lot of code samples online deal with how to generate a public key from a certificate using SecCertificateCreateWithData

此外:512位的生成速度很快,但是却一文不值.对结果满意后,请选择更长且安全的值.

Also: 512 bit is fast to generate but worthless. Pick a longer and secure value once you're satisfied with the results.

在导入生成和导出的密钥时,我得到了有效的结果,因此我认为它是有效的,但是我没有尝试使用它进行加密和解密.

I got valid results back when importing the key I generated and exported, so I assume it works, but I did not try to encrypt and decrypt with it.

这篇关于Swift 3将SecKey导出到String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆