iPhone 使用证书加密

标签 iphone security encryption sdk openssl

我必须加密一个字符串,并在 xCode 项目的 Resources 文件夹中包含一个 .CER (x.509)。这两天我一直在想怎么做,但没有成功,所以是时候问了。

Apple 的文档非常难以阅读...而且我发现这个框架可能是最难理解的...两个示例都没有帮助。

所以,我尝试了以下代码:显然它不起作用:

在我的 Mac 上,我使用了 OPENSSL,但我发现无法在 SDK 中重新创建 OPENSSL 命令。所以,我很困惑...有人吗???

非常感谢:)

NSString *certPath = [[NSBundle mainBundle] pathForResource:@"Certificate" ofType:@"cer"]; 
    SecCertificateRef myCertificate = nil;

    NSData *certificateData = [[NSData alloc] initWithContentsOfFile:certPath]; 
    myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certificateData);

    SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
    SecTrustRef myTrust;
    SecTrustCreateWithCertificates(myCertificate, myPolicy, &myTrust);
    SecKeyRef publicKey = SecTrustCopyPublicKey(myTrust);



        uint8_t *pPlainText = (uint8_t*)"This is a test";
        uint8_t aCipherText[1024];
        size_t iCipherLength = 1024;
        OSStatus status = SecKeyEncrypt(publicKey,
                                        kSecPaddingPKCS1,
                                        pPlainText,
                                        strlen( (char*)pPlainText ) + 1,
                                        aCipherText,
                                        &iCipherLength);


        }

最佳答案

我尝试了您更新的代码,并在末尾添加了两行:

NSData *cipherData = [NSData dataWithBytes:aCipherText length:iCipherLength];
NSLog(@"(%d) %@", status, cipherData);

效果很好:

2011-02-17 22:24:04.204 Untitled[45121:207] (0) <87a2eb07 25ab693a 7fe88329 974b6820
843c5c33 8c5d4606 aecea682 0176e4cb 10482c9b fd2e2242 1c77d349 d3037e91 8d704783
f2e04c82 ef273815 bdb6aa73 f8646542 243f3e12 518147ba 53636441 fd9399d3 b198ed6a
615d51d1 4105fb75 27180f0d 09835551 5162e156 33dedf39 a87e17f8 16881990 c5e57a38
7cd7ec63>

现在的一个区别是我使用的公钥位于我的钥匙串(keychain)中。如果您的不是,您可能需要查看下面的 importing-an-ssl-cert-under-the-iphone-sdk 链接。到目前为止,我只在模拟器上进行了测试,模拟器也可能有所不同,但我相信这是正确的。

如果您仍然遇到问题,请确保检查每个调用的结果(如果它返回 OSStatus,请检查)。哪一 block 失败了?

<小时/>

您忘记调用SecTrustEvaluate()在您的SecTrustRef上在调用SecTrustCopyPublicKey()之前。检查 SecTrustCopyPublicKey() 上的文档这解释了这一点。

<小时/>

不太有用的旧信息:

我相信这些帖子应该为您指明正确的方向:

http://greghaygood.com/2009/01/17/asymmetric-encryption-with-the-iphone-sdk-and-securityframework

Importing an SSL cert under the iPhone SDK

另请注意,如果您已有适用于 Mac 的 OpenSSL 代码,则可以编译适用于 iPhone 的 OpenSSL。当我开发构建脚本时,这篇文章对我很有用:

http://www.therareair.com/2009/01/01/tutorial-how-to-compile-openssl-for-the-iphone/

关于iPhone 使用证书加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5019185/

相关文章:

iOS 8 : Mapkit error throws an : Must call -[CLLocationManager requestWhenInUseAuthorization]

python - Ruby 中是否有等同于 yaml.safe_load 的东西?

java - 将数据从 Perl 脚本交换到 Java Android 应用程序的最简单安全方法

java - java加密字符串,node.js解密,报错: bad decrypt

iphone - 如何每 4-5 秒获取距用户位置的距离

iphone - 最低操作系统版本不正确

iphone - 以编程方式更改 iPhone 背景

php - 使用 SSL 真的可以防止黑客入侵我的 session 变量吗?

php - 保护和加密客户端和服务器之间的连接

c++ - OpenSSL : Encrypt a symmetric key with an ECC public key