ios - 如何从存储在 iOS 钥匙串(keychain)中的 key 获取 DER 格式的公钥?

标签 ios swift security keychain public-key

我正在使用以下代码创建 key

let tag = "com.example.keys.mykey".data(using: .utf8)!
let attributes: [String: Any] =
[kSecAttrKeyType as String:            kSecAttrKeyTypeECSECPrimeRandom,
 kSecAttrKeySizeInBits as String:      256,
 kSecPrivateKeyAttrs as String:
    [kSecAttrIsPermanent as String:    true,
     kSecAttrApplicationTag as String: tag]]
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error}

获取公钥使用

let publicKey = SecKeyCopyPublicKey(privateKey)

最佳答案

 func addDerKeyInfo(rawPublicKey:[UInt8]) -> [UInt8] {
    let DerHdrSubjPubKeyInfo:[UInt8]=[
        /* Ref: RFC 5480 - SubjectPublicKeyInfo's ASN encoded header */
        0x30, 0x59, /* SEQUENCE */
        0x30, 0x13, /* SEQUENCE */
        0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01, /* oid: 1.2.840.10045.2.1   */
        0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07, /* oid: 1.2.840.10045.3.1.7 */
        0x03, 0x42, /* BITSTRING */
        0x00 /* unused number of bits in bitstring, followed by raw public-key bits */]
    let derKeyInfo = DerHdrSubjPubKeyInfo + rawPublicKey
    return derKeyInfo
}

func convertbase64StringToByteArray(base64String: String) -> [UInt8] {
    if let nsdata = NSData(base64Encoded: base64String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)  {
        var bytes = [UInt8](repeating: 0, count: nsdata.length)
        nsdata.getBytes(&bytes,length: nsdata.length)
        return bytes
    }
    else
    {
        print("Invalid base64 String")
    }
}
func convertSecKeyToDerKeyFormat(publicKey:SecKey) throws -> String
{
    do
    {
        if let externalRepresentationOfPublicKey = SecKeyCopyExternalRepresentation(publicKey,&error)
        {
            let derKeyFormat = externalRepresentationOfPublicKey as Data
            var publicKeyByteArray = try convertbase64StringToByteArray(base64String: derKeyFormat.base64EncodedString())
            publicKeyByteArray =  addDerKeyInfo(rawPublicKey: publicKeyByteArray)
            let base64EncodedPublicKey:String=Data(publicKeyByteArray).base64EncodedString()
            return base64EncodedPublicKey
        }
        else
        {
            throw error as! Error
        }
    }
    catch
    {
        throw error
    }
}

通过将公钥传递给它来调用 convertSecKeyToDerKeyFormat 函数。

关于ios - 如何从存储在 iOS 钥匙串(keychain)中的 key 获取 DER 格式的公钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053152/

相关文章:

security - 如何使用 WScript.Shell 对象调试 ASP 权限问题?

c# - 从 c# 将敏感信息存储在 keepass 数据库中

swift - 使用 Firebase 的 OAuth 问题通过 Facebook 登录(input_token 中的 App_id 与查看应用程序不匹配)

ios - 这些 MPMediaQuery 结果之间有什么区别?

iphone - 请求超时,找不到指定的服务器

ios - 无法调用非功能类型double的值

swift - Swift 中的段错误

ios - 在 downloadTask 完成后执行 segue

java - 我怎么知道当前有效的java.policy

ios - Swift:水平滚动 UITextView