2

I have a public key stored in a PEM file and I would like to load this file and extract the public key into an NSData that I can then send to [SecKeyWrapper addPeerPublicKey:keyBits:] (cf. http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Listings/Classes_SecKeyWrapper_h.html).

How can I do that in Objective-C (on iOS)?

Sebastien
  • 3,583
  • 4
  • 43
  • 82

1 Answers1

3

Assuming you know the public key exists and begins with "-----BEGIN PUBLIC KEY-----" and ends with "-----END PUBLIC KEY-----" you could do the following:

NSString *startPublicKey = @"-----BEGIN PUBLIC KEY-----";
NSString *endPublicKey = @"-----END PUBLIC KEY-----";
NSString* path = [[NSBundle mainBundle] pathForResource:@"mykey"
                                                     ofType:@"pem"];
NSString* content = [NSString stringWithContentsOfFile:path
                                                  encoding:NSUTF8StringEncoding
                                                     error:NULL];
NSString *publicKey;
NSScanner *scanner = [NSScanner scannerWithString:content];
[scanner scanUpToString:startPublicKey intoString:nil];
[scanner scanString:startPublicKey intoString:nil];
[scanner scanUpToString:endPublicKey intoString:&publicKey];

NSData *data = [NSData base64DataFromString:publicKey];
Matt Dearing
  • 9,286
  • 1
  • 23
  • 25