簡體   English   中英

使用密碼加載X509 pem證書。 目標C.

[英]Loading a X509 pem certificate with password. Objective C

我是Objective-c和iOS編程的全新手。

我需要使用REST API,其中請求需要使用x509 PEM證書文件和證書密碼進行相互SSL身份驗證。

我的問題是我真的不知道如何在目標C中做到這一點,在C#中它會像以下一樣簡單:

X509Certificate2 myCertificate = new x509Certificate2(certificatePath, certificatePassword);
myRequest.ClientCertificate.Add(myCertificate);

其中"myRequest"只表示http請求的變量。

我一直在很多論壇和帖子中尋找一段時間,包括一些舊的stackoverflow問題。 人們給出的主要提示是“使用OpenSSL”,但我已經在少數幾個地方讀過(我認為即使在stackoverflow問題中)Apple已經棄用了OpenSSL。

問題: 如何使用其密碼加載.pem x509證書,以使用Objective-C語言將POST請求發送到外部REST API服務?

謝謝。

我自己的解決方案:

使用OpenSSL命令轉換.pem文件介紹pkcs12證書:

openssl pkcs12 -export -in "certificateFile" -inkey "KeyFile" -out "certificate.p12"

然后設置本教程中的一些代碼: https//vanjakom.wordpress.com/tag/nsurlconnection/

基本上:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"Authentication challenge");

    // load cert
    NSString *path = [[NSBundle mainBundle] pathForResource:@"userA" ofType:@"p12"];
    NSData *p12data = [NSData dataWithContentsOfFile:path];
    CFDataRef inP12data = (__bridge CFDataRef)p12data;

    SecIdentityRef myIdentity;
    SecTrustRef myTrust;
    OSStatus status = extractIdentityAndTrust(inP12data, &myIdentity, &myTrust);

    SecCertificateRef myCertificate;
    SecIdentityCopyCertificate(myIdentity, &myCertificate);
    const void *certs[] = { myCertificate };
    CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);

    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:myIdentity certificates:(__bridge NSArray*)certsArray persistence:NSURLCredentialPersistencePermanent];

    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

OSStatus extractIdentityAndTrust(CFDataRef inP12data, SecIdentityRef *identity, SecTrustRef *trust)
{
    OSStatus securityError = errSecSuccess;

    CFStringRef password = CFSTR("userA");
    const void *keys[] = { kSecImportExportPassphrase };
    const void *values[] = { password };

    CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    securityError = SecPKCS12Import(inP12data, options, &items);

    if (securityError == 0) {
        CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
        const void *tempIdentity = NULL;
        tempIdentity = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity);
        *identity = (SecIdentityRef)tempIdentity;
        const void *tempTrust = NULL;
        tempTrust = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust);
        *trust = (SecTrustRef)tempTrust;
    }

    if (options) {
        CFRelease(options);
    }

    return securityError;
}

“從教程中復制的代碼,沒有根據我自己的需要復制我自己的修改”。

它已經解決了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM