如何在X509证书中从p12获取私钥

时间:2017-09-02 03:35:41

标签: ssl swift3 ssl-certificate

我需要集成我的iOS应用程序来使用Web服务需要客户端证书。我使用以下代码从X509证书中的p12中提取私钥。 我找到了这段代码但没有工作,我把它翻译成了swift 3。

func privateKeyFromCertificate() -> SecKeyRef {

    let certName : String = //name of the certificate//

    let resourcePath: String = NSBundle.mainBundle().pathForResource(certName, ofType: "p12")!

    let p12Data: NSData = NSData(contentsOfFile: resourcePath)!

    let key : NSString = kSecImportExportPassphrase as NSString
    let options : NSDictionary = [key : "password_for_certificate"]

    var privateKeyRef: SecKeyRef? = nil

    var items : CFArray?

    let securityError: OSStatus = SecPKCS12Import(p12Data, options, &items)

    //let description : CFString = CFCopyDescription(items)
    //print(description)

    let theArray : CFArray = items!

    if securityError == noErr && CFArrayGetCount(theArray) > 0 {
        let newArray = theArray as [AnyObject] as NSArray
        let dictionary = newArray.objectAtIndex(0)
        let secIdentity = dictionary.valueForKey(kSecImportItemIdentity as String) as! SecIdentityRef
        let securityError = SecIdentityCopyPrivateKey(secIdentity , &privateKeyRef)
        if securityError != noErr {
            privateKeyRef = nil
        }
    }
    return privateKeyRef!
}

错误遭遇: 让secIdentity = dictionary.valueForKey(kSecImportItemIdentity as String)为! SecIdentityRef

以下更新版本在同一行有同样的问题:

   func privateKeyFromCertificate() -> SecKey {       
        let certName : String = "certficateName"
        let resourcePath: String = Bundle.main.path(forResource: certName, ofType: "p12")!
        let p12Data: NSData = NSData(contentsOfFile: resourcePath)!
        let key : NSString = kSecImportExportPassphrase as NSString
        let options : NSDictionary = [key : "password_for_certificate"]
        var privateKeyRef: SecKey? = nil
        var items : CFArray?
        let securityError: OSStatus = SecPKCS12Import(p12Data, options, &items)
        //let description : CFString = CFCopyDescription(items)
        //print(description)
        let theArray : CFArray = items!
        if securityError == noErr && CFArrayGetCount(theArray) > 0 {
            let newArray = theArray as [AnyObject] as NSArray
            let dictionary = newArray.object(at: 0)
//- encounter error here:
            let secIdentity = (dictionary as AnyObject).value(kSecImportItemIdentity as String) as! SecIdentity

            let securityError = SecIdentityCopyPrivateKey(secIdentity , &privateKeyRef)
            if securityError != noErr {
                privateKeyRef = nil
            }
        }
        return privateKeyRef!
    }

我收到以下错误:

让secIdentity =(字典为AnyObject).value(kSecImportItemIdentity as String)为! SecIdentity

无法调用'价值'使用Type'(String)'

的任何参数列表

非常感谢您的帮助。

由于

1 个答案:

答案 0 :(得分:0)

你可以尝试这个错误块 - 把它们放在条件id let块中。

java.util.ArrayList