如何从存储在 iOS 钥匙串中的密钥中获取 DER 格式的公钥?

Posted

技术标签:

【中文标题】如何从存储在 iOS 钥匙串中的密钥中获取 DER 格式的公钥?【英文标题】:How to get public key in DER format from key stored in iOS keychain? 【发布时间】:2017-11-01 10:49:22 【问题描述】:

我正在使用以下代码创建密钥

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)

【问题讨论】:

【参考方案1】:
 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 函数。

【讨论】:

非常感谢!为我节省了很多时间。不幸的是,Apple 仅支持 Mac 机器的 ASN.1,不支持 ios

以上是关于如何从存储在 iOS 钥匙串中的密钥中获取 DER 格式的公钥?的主要内容,如果未能解决你的问题,请参考以下文章

在钥匙串中存储用于加密密码的密钥的最佳位置在哪里

检索钥匙串中的数据以获取在 ios 中不起作用的特定服务

以编程方式在 OS X 钥匙串中存储对称密钥

访问钥匙串中的安全项目有时会在 iOS 中返回错误 -25308 (errSecInteractionNotAllowed)

使用 Jenkins/Hudson 作为 iOS 和 Mac 开发的持续集成时,钥匙串中缺少证书和密钥

ASPasswordCredential - 从哪里来?