How to create private key from file in Objective C

2019-06-28 00:21发布

I have created a public key like this:

 NSString *pkFilePath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
NSData *myCertData = [NSData dataWithContentsOfFile:pkFilePath];


SecCertificateRef cert = SecCertificateCreateWithData (kCFAllocatorDefault, (CFDataRef)myCertData);
CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, (const void **) &cert, 1, NULL);

SecTrustRef trust;
SecPolicyRef myPolicy   = SecPolicyCreateBasicX509();
SecTrustCreateWithCertificates(certs, myPolicy, &trust);
SecTrustResultType trustResult;
SecTrustEvaluate(trust, &trustResult);
SecKeyRef pub_key_leaf = SecTrustCopyPublicKey(trust);
NSLog(@"%@",pub_key_leaf);

But how to create private key from file?

Here is some related code to create a private key but I am not getting how to create private key from this using my privatekey file.

https://developer.apple.com/library/mac/#documentation/security/conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html#//apple_ref/doc/uid/TP40001358-CH208-SW10

2条回答
姐就是有狂的资本
2楼-- · 2019-06-28 00:34

I had the same problem, it turns out you need to use a p12 file to import the private key.

See my answer here https://stackoverflow.com/a/17295321/480467

查看更多
一纸荒年 Trace。
3楼-- · 2019-06-28 00:46

AFAIK there is no easy way to create a SecPrivateKeyRef from NSData. If at all possible - combine your private & public file into a p12:

openssl pkcs12 -export -out combined.p12 -in public.der -inform DER -inkey private...
Password: 12345678

and then do

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: @"12345678", kSecImportExportPassphrase, nil];

OSStatus status = SecPKCS12Import((__bridge CFDataRef)pkcs12derAsData,  
     (__bridge CFDictionaryRef)options, &items);

In the cases where I had to deal with DER/PEM - I've found it easiest to link with openssl. And take it from there.

Dw.

查看更多
登录 后发表回答