2014-03-06 121 views
1

我想的NSData以下方法进行加密:RSA加密使用现有的公共密钥

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

}

,里面写到“公用钥匙HERE”我要加载现有的公共键我已经复制到我的包。我怎样才能做到这一点?

+0

你怎么复制到你的包吗? – Rajesh

+0

只是把它拖入xcode ... – davidOhara

+0

这是一个字符串的文件吗? – Rajesh

回答

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]; 
    // ... 
} 
+0

我给出了一个结论...并且公钥必须具有* .pem扩展名! – davidOhara

+1

不,您使用的是'DER'格式的证书,例如'cer'扩展名。您可以使用“钥匙串访问”工具创建新的密钥对。例如,创建一个自签名的根证书。它将包含公钥和私钥。 – Flovdis

+0

啊好的...我应该在Keychain中使用哪种证书类型?有几个... – davidOhara