我正在尝试使用以下方法加密NSData:
- (NSData *) encryptWithData:(NSData *)content {
size_t plainLen = [content length];
void *plain = malloc(plainLen);
[content getBytes:plain
length:plainLen];
size_t cipherLen = 256;
void *cipher = malloc(cipherLen);
OSStatus returnCode = SecKeyEncrypt("PUBLIC KEY HERE", kSecPaddingPKCS1, plain,
plainLen, cipher, &cipherLen);
NSData *result = nil;
if (returnCode != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %ld", returnCode);
}
else {
result = [NSData dataWithBytes:cipher
length:cipherLen];
}
free(plain);
free(cipher);
return result;
}
在哪里写“PUBLIC KEY HERE”我想加载一个已经复制到我的包中的现有公钥。我怎么能这样做?
答案 0 :(得分:2)
例如,使用包含公钥的证书文件:
NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL options:0 error:&error];
if (certificateData) {
SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certificateData));
// ...
SecKeyRef publicKey;
SecCertificateCopyPublicKey(certificate, &publicKey);
// ...
}
从捆绑包中加载数据:
NSArray *certificateURLs = [[NSBundle mainBundle] URLsForResourcesWithExtension:@"cer" subdirectory:@"myCertificates"];
for (NSURL *certificateURL in certificateURLs) {
NSData *certificateData = [NSData dataWithContentsOfURL:certificateURL options:0 error:&error];
// ...
}