问题
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
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/15902653/how-to-create-private-key-from-file-in-objective-c