我有一个存储在PEM文件中的公钥,我想加载这个文件并将公钥提取到NSData中,然后我可以发送到[SecKeyWrapper addPeerPublicKey:keyBits:](参见http://developer.apple.com/library/ios/#samplecode/CryptoExercise/Listings/Classes_SecKeyWrapper_h.html )。
我如何在Objective-C(在iOS上)上做到这一点?
答案 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];