Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

encryption - iPhone: How to create a SecKeyRef from a public key file (PEM)

In order to send and receive encrypted messages from/to the iPhone I need to read a public key (server's public key) PEM file and create a SecKeyRef (later I could even store it on the keychain in order not to create it again).

This is my current workflow:

  1. On the server: Create a P12 file with the user's certificate and private key. Store the user's public key on the server's keychain.
  2. On the iPhone: Retrieve the P12 file from the server, use the password to open it and store the private key on the keychain.
  3. On the iPhone: Retrieve a PEM file with the server's public key from the server. Create a SecKeyRef and store it on the keychain
  4. On the iPhone: use both keys to send/receive encrypted messages to/from the server.
  5. Live happily ever after.

I'm having problems with 3, as I cannot create a SecKeyRef from the PEM file data. I cannot find any documentation on how to do it, Did anybody had the same problem? Any hints? As I cannot find any code examples or documentation on this it feels that I'm doing something wrong...

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should be able to interpret a DER encoded pem and get a cert using SecCertificateCreateWithData() from which you can then extract a key;

NSData *myCertData = ....;

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

SecTrustRef trust;
SecTrustCreateWithCertificates(certs, policy, &trust);
SecTrustResultType trustResult;
SecTrustEvaluate(trust, &trustResult);
SecKeyRef pub_key_leaf = SecTrustCopyPublicKey(trust);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...