【问题标题】:RSA Encryption using existing public key使用现有公钥的 RSA 加密
【发布时间】:2014-04-08 17:39:59
【问题描述】:

我正在尝试使用以下方法加密 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" 我想加载一个我已经复制到我的捆绑包中的现有公钥。我该怎么做?

【问题讨论】:

  • 你是如何复制到你的包的?
  • 只是把它拖进xcode...
  • 那是字符串的文件吗?
  • 获取你拖拽的文件内容并作为key使用

标签: ios iphone encryption ios7 public-key-encryption


【解决方案1】:

例如使用包含公钥的证书文件:

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

【讨论】:

  • 我试一试...公钥必须有 *.pem 扩展名?!
  • 不,您使用的是DER 格式的证书,并具有例如cer 扩展名。您可以使用“钥匙串访问”工具创建新的密钥对。例如创建一个自签名根证书。它将包含一个公钥和私钥。
  • 您可以使用 S/MIME 证书。这将允许您对数据进行签名和加密。最后也没什么大不了的。区别只是为证书验证设置的标志。但是,当您以编程方式使用证书时,您可以忽略这些标志。
  • 感谢您的帮助..但如果我创建一个 s/mime 证书,我只能将私钥导出为 *.cer!公钥仅作为钥匙串中的 *.pem...
  • 1.右键单击新证书。 2.选择“导出” 3.将导出格式改为“.cer”
猜你喜欢
  • 1970-01-01
  • 2011-11-10
  • 2014-06-23
  • 2011-11-07
  • 2013-05-07
  • 2014-01-07
  • 2013-06-08
  • 2011-08-16
相关资源
最近更新 更多