将公钥从PEM文件加载到NSData

时间:2013-05-31 20:28:20

标签: ios objective-c security pem

我有一个存储在PEM文件中的公钥,我想加载这个文件并将公钥提取到NSData中,然后我可以发送到[SecKeyWrapper addPeerPublicKey:keyBits:](参见http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Listings/Classes_SecKeyWrapper_h.html )。

我如何在Objective-C(在iOS上)上做到这一点?

1 个答案:

答案 0 :(得分:3)

假设您知道公钥存在并以“----- BEGIN PUBLIC KEY -----”开头并以“----- END PUBLIC KEY -----”结尾,您可以以下内容:

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];