在iOS中使用RSA加密解密,需要用到.der
和.p12
后缀格式的文件,其中.der
格式的文件存放的是公钥(Public key)用于加密,.p12
格式的文件存放的是私钥(Private key)用于解密. 首先需要先生成这些文件,然后再将文件导入工程使用,不多说,开始做!
一、使用openssl生成所需秘钥文件
生成环境是在mac系统下,使用openssl进行生成,首先打开终端,按下面这些步骤依次来做:
1. 生成模长为1024bit的私钥文件private_key.pem
openssl genrsa -out private_key.pem 1024
2. 生成证书请求文件rsaCertReq.csr
openssl req -new -key private_key.pem -out rsaCerReq.csr
注意:这一步会提示输入国家、省份、mail等信息,可以根据实际情况填写,或者全部不用填写,直接全部敲回车.
3. 生成证书rsaCert.crt
,并设置有效时间为1年
openssl x509 -req -days 3650 -in rsaCerReq.csr -signkey private_key.pem -out rsaCert.crt
4. 生成供iOS使用的公钥文件public_key.der
openssl x509 -outform der -in rsaCert.crt -out public_key.der
5. 生成供iOS使用的私钥文件private_key.p12
openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt
注意:这一步会提示给私钥文件设置密码,直接输入想要设置密码即可,然后敲回车,然后再验证刚才设置的密码,再次输入密码,然后敲回车,完毕!
在解密时,private_key.p12
文件需要和这里设置的密码配合使用,因此需要牢记此密码.
6. 生成供Java使用的公钥rsa_public_key.pem
openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout
7. 生成供Java使用的私钥pkcs8_private_key.pem
openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt
全部执行成功后,会生成如下文件,其中public_key.der
和private_key.p12
就是iOS需要用到的文件,如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/c56fc3bae5ed383f0d59d8337b4560f5.webp?x-image-process=image/format,png)
二、将文件导入工程使用
1.新建工程, 并导入Security.framework
框架, 如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/4105139d3a62fa7ef6881ee5b76255a7.webp?x-image-process=image/format,png)
2.导入秘钥文件
导入.der
和.p12
格式的秘钥文件, 如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/b2283df1612528292d9f4030cc63aa29.webp?x-image-process=image/format,png)
3.新建用于加密、解密的类RSAEncryptor
, 并实现相关方法
新建RSAEncryptor
类, 如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/f22fb281cd6d06d2aefc2e3109e80975.webp?x-image-process=image/format,png)
下面开始上代码, 可以直接复制过去用:
RSAEncryptor.h
代码如下:
<code class="objectivec"><span style="font-size: 18px;"><span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title"><Foundation/Foundation.h></span></span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@interface</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">RSAEncryptor</span> : <span class="hljs-title" style="color: rgb(102, 0, 102);">NSObject</span></span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">/** * 加密方法 * * @param str 需要加密的字符串 * @param path '.der'格式的公钥文件路径 */</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)encryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str publicKeyWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)path; <span class="hljs-comment" style="color: rgb(136, 0, 0);">/** * 解密方法 * * @param str 需要解密的字符串 * @param path '.p12'格式的私钥文件路径 * @param password 私钥文件密码 */</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)decryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str privateKeyWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)path password:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)password; <span class="hljs-comment" style="color: rgb(136, 0, 0);">/** * 加密方法 * * @param str 需要加密的字符串 * @param pubKey 公钥字符串 */</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)encryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str publicKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)pubKey; <span class="hljs-comment" style="color: rgb(136, 0, 0);">/** * 解密方法 * * @param str 需要解密的字符串 * @param privKey 私钥字符串 */</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)decryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str privateKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)privKey; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span></span></code>
RSAEncryptor.m
代码如下:
<code class="objectivec"><span style="font-size: 18px;"><span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title">"RSAEncryptor.h"</span></span> <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title"><Security/Security.h></span></span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@implementation</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">RSAEncryptor</span></span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *base64_encode_data(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data){ data = [data base64EncodedDataWithOptions:<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *ret = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> alloc] initWithData:data encoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *base64_decode(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *str){ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> alloc] initWithBase64EncodedString:str options:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSDataBase64DecodingIgnoreUnknownCharacters</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> data; } <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#pragma mark - 使用'.der'公钥文件加密</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">//加密</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)encryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str publicKeyWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)path{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!str || !path) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> encryptString:str publicKeyRef:[<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> getPublicKeyRefWithContentsOfFile:path]]; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">//获取公钥</span> + (SecKeyRef)getPublicKeyRefWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)filePath{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *certData = [<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> dataWithContentsOfFile:filePath]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!certData) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } SecCertificateRef cert = SecCertificateCreateWithData(<span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>, (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDataRef</span>)certData); SecKeyRef key = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>; SecTrustRef trust = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>; SecPolicyRef policy = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (cert != <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>) { policy = SecPolicyCreateBasicX509(); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (policy) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (SecTrustCreateWithCertificates((<span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFTypeRef</span>)cert, policy, &trust) == noErr) { SecTrustResultType result; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (SecTrustEvaluate(trust, &result) == noErr) { key = SecTrustCopyPublicKey(trust); } } } } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (policy) <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(policy); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (trust) <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(trust); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (cert) <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(cert); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> key; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)encryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str publicKeyRef:(SecKeyRef)publicKeyRef{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(![str dataUsingEncoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>]){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!publicKeyRef){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> encryptData:[str dataUsingEncoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>] withKeyRef:publicKeyRef]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *ret = base64_encode_data(data); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#pragma mark - 使用'.12'私钥文件解密</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">//解密</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)decryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str privateKeyWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)path password:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)password{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!str || !path) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!password) password = <span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> decryptString:str privateKeyRef:[<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> getPrivateKeyRefWithContentsOfFile:path password:password]]; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">//获取私钥</span> + (SecKeyRef)getPrivateKeyRefWithContentsOfFile:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)filePath password:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span>*)password{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *p12Data = [<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> dataWithContentsOfFile:filePath]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!p12Data) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } SecKeyRef privateKeyRef = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> * options = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> alloc] init]; [options setObject: password forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecImportExportPassphrase]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFArrayRef</span> items = <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFArrayCreate</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>, <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>); OSStatus securityError = SecPKCS12Import((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDataRef</span>) p12Data, (__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)options, &items); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (securityError == noErr && <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFArrayGetCount</span>(items) > <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>) { <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span> identityDict = <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFArrayGetValueAtIndex</span>(items, <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>); SecIdentityRef identityApp = (SecIdentityRef)<span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryGetValue</span>(identityDict, kSecImportItemIdentity); securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (securityError != noErr) { privateKeyRef = <span class="hljs-literal" style="color: rgb(0, 102, 102);">NULL</span>; } } <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(items); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> privateKeyRef; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)decryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str privateKeyRef:(SecKeyRef)privKeyRef{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> alloc] initWithBase64EncodedString:str options:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSDataBase64DecodingIgnoreUnknownCharacters</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!privKeyRef) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> decryptData:data withKeyRef:privKeyRef]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *ret = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> alloc] initWithData:data encoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#pragma mark - 使用公钥字符串加密</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">/* START: Encryption with RSA public key */</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">//使用公钥字符串加密</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)encryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str publicKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)pubKey{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> encryptData:[str dataUsingEncoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>] publicKey:pubKey]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *ret = base64_encode_data(data); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)encryptData:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)data publicKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)pubKey{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!data || !pubKey){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } SecKeyRef keyRef = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> addPublicKey:pubKey]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!keyRef){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> encryptData:data withKeyRef:keyRef]; } + (SecKeyRef)addPublicKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)key{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> spos = [key rangeOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"-----BEGIN PUBLIC KEY-----"</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> epos = [key rangeOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"-----END PUBLIC KEY-----"</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> != <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNotFound</span> && epos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> != <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNotFound</span>){ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUInteger</span> s = spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> + spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.length</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUInteger</span> e = epos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> range = <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMakeRange</span>(s, e-s); key = [key substringWithRange:range]; } key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\r"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\n"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\t"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@" "</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// This will be base64 encoded, decode it.</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = base64_decode(key); data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> stripPublicKeyHeader:data]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!data){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">//a tag to read/write keychain storage</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *tag = <span class="hljs-string" style="color: rgb(0, 136, 0);">@"RSAUtil_PubKey"</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *d_tag = [<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> dataWithBytes:[tag UTF8String] length:[tag length]]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Delete any old lingering key with the same tag</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> *publicKey = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> alloc] init]; [publicKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecClassKey forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecClass]; [publicKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyTypeRSA forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrKeyType]; [publicKey setObject:d_tag forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrApplicationTag]; SecItemDelete((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)publicKey); <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Add persistent version of the key to system keychain</span> [publicKey setObject:data forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecValueData]; [publicKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyClassPublic forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyClass]; [publicKey setObject:[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNumber</span> numberWithBool:<span class="hljs-literal" style="color: rgb(0, 102, 102);">YES</span>] forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecReturnPersistentRef]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFTypeRef</span> persistKey = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; OSStatus status = SecItemAdd((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)publicKey, &persistKey); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (persistKey != <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>){ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(persistKey); } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> ((status != noErr) && (status != errSecDuplicateItem)) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } [publicKey removeObjectForKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecValueData]; [publicKey removeObjectForKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecReturnPersistentRef]; [publicKey setObject:[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNumber</span> numberWithBool:<span class="hljs-literal" style="color: rgb(0, 102, 102);">YES</span>] forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecReturnRef]; [publicKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyTypeRSA forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrKeyType]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Now fetch the SecKeyRef version of the key</span> SecKeyRef keyRef = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; status = SecItemCopyMatching((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)publicKey, (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFTypeRef</span> *)&keyRef); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(status != noErr){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> keyRef; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)stripPublicKeyHeader:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)d_key{ <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Skip ASN.1 public key header</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (d_key == <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">long</span> len = [d_key length]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!len) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> *c_key = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> *)[d_key bytes]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idx = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (c_key[idx++] != <span class="hljs-number" style="color: rgb(0, 102, 102);">0x30</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (c_key[idx] > <span class="hljs-number" style="color: rgb(0, 102, 102);">0x80</span>) idx += c_key[idx] - <span class="hljs-number" style="color: rgb(0, 102, 102);">0x80</span> + <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span> idx++; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// PKCS #1 rsaEncryption szOID_RSA_RSA</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> seqiod[] = { <span class="hljs-number" style="color: rgb(0, 102, 102);">0x30</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x0d</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x06</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x09</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x2a</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x86</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x48</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x86</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0xf7</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x0d</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x01</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x01</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x01</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x05</span>, <span class="hljs-number" style="color: rgb(0, 102, 102);">0x00</span> }; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (memcmp(&c_key[idx], seqiod, <span class="hljs-number" style="color: rgb(0, 102, 102);">15</span>)) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); idx += <span class="hljs-number" style="color: rgb(0, 102, 102);">15</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (c_key[idx++] != <span class="hljs-number" style="color: rgb(0, 102, 102);">0x03</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (c_key[idx] > <span class="hljs-number" style="color: rgb(0, 102, 102);">0x80</span>) idx += c_key[idx] - <span class="hljs-number" style="color: rgb(0, 102, 102);">0x80</span> + <span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span> idx++; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (c_key[idx++] != <span class="hljs-string" style="color: rgb(0, 136, 0);">'\0'</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Now make a new NSData from this buffer</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ([<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> dataWithBytes:&c_key[idx] length:len - idx]); } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)encryptData:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)data withKeyRef:(SecKeyRef) keyRef{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">const</span> uint8_t *srcbuf = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">const</span> uint8_t *)[data bytes]; size_t srclen = (size_t)data<span class="hljs-variable" style="color: rgb(102, 0, 102);">.length</span>; size_t block_size = SecKeyGetBlockSize(keyRef) * <span class="hljs-keyword" style="color: rgb(0, 0, 136);">sizeof</span>(uint8_t); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span> *outbuf = malloc(block_size); size_t src_block_size = block_size - <span class="hljs-number" style="color: rgb(0, 102, 102);">11</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableData</span> *ret = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableData</span> alloc] init]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span>(<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idx=<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; idx<srclen; idx+=src_block_size){ <span class="hljs-comment" style="color: rgb(136, 0, 0);">//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);</span> size_t data_len = srclen - idx; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(data_len > src_block_size){ data_len = src_block_size; } size_t outlen = block_size; OSStatus status = noErr; status = SecKeyEncrypt(keyRef, kSecPaddingPKCS1, srcbuf + idx, data_len, outbuf, &outlen ); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (status != <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>) { <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"SecKeyEncrypt fail. Error Code: %d"</span>, status); ret = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">break</span>; }<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{ [ret appendBytes:outbuf length:outlen]; } } free(outbuf); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(keyRef); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">/* END: Encryption with RSA public key */</span> <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#pragma mark - 使用私钥字符串解密</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">/* START: Decryption with RSA private key */</span> <span class="hljs-comment" style="color: rgb(136, 0, 0);">//使用私钥字符串解密</span> + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)decryptString:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)str privateKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)privKey{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!str) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> alloc] initWithBase64EncodedString:str options:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSDataBase64DecodingIgnoreUnknownCharacters</span>]; data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> decryptData:data privateKey:privKey]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *ret = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> alloc] initWithData:data encoding:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUTF8StringEncoding</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)decryptData:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)data privateKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)privKey{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!data || !privKey){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } SecKeyRef keyRef = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> addPrivateKey:privKey]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!keyRef){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> decryptData:data withKeyRef:keyRef]; } + (SecKeyRef)addPrivateKey:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *)key{ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> spos = [key rangeOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"-----BEGIN RSA PRIVATE KEY-----"</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> epos = [key rangeOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"-----END RSA PRIVATE KEY-----"</span>]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> != <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNotFound</span> && epos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> != <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNotFound</span>){ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUInteger</span> s = spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span> + spos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.length</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSUInteger</span> e = epos<span class="hljs-variable" style="color: rgb(102, 0, 102);">.location</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSRange</span> range = <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMakeRange</span>(s, e-s); key = [key substringWithRange:range]; } key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\r"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\n"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"\t"</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; key = [key stringByReplacingOccurrencesOfString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@" "</span> withString:<span class="hljs-string" style="color: rgb(0, 136, 0);">@""</span>]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// This will be base64 encoded, decode it.</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *data = base64_decode(key); data = [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">self</span> stripPrivateKeyHeader:data]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(!data){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">//a tag to read/write keychain storage</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *tag = <span class="hljs-string" style="color: rgb(0, 136, 0);">@"RSAUtil_PrivKey"</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *d_tag = [<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> dataWithBytes:[tag UTF8String] length:[tag length]]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Delete any old lingering key with the same tag</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> *privateKey = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableDictionary</span> alloc] init]; [privateKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecClassKey forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecClass]; [privateKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyTypeRSA forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrKeyType]; [privateKey setObject:d_tag forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrApplicationTag]; SecItemDelete((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)privateKey); <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Add persistent version of the key to system keychain</span> [privateKey setObject:data forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecValueData]; [privateKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyClassPrivate forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyClass]; [privateKey setObject:[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNumber</span> numberWithBool:<span class="hljs-literal" style="color: rgb(0, 102, 102);">YES</span>] forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecReturnPersistentRef]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFTypeRef</span> persistKey = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; OSStatus status = SecItemAdd((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)privateKey, &persistKey); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (persistKey != <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>){ <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(persistKey); } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> ((status != noErr) && (status != errSecDuplicateItem)) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } [privateKey removeObjectForKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecValueData]; [privateKey removeObjectForKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecReturnPersistentRef]; [privateKey setObject:[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSNumber</span> numberWithBool:<span class="hljs-literal" style="color: rgb(0, 102, 102);">YES</span>] forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecReturnRef]; [privateKey setObject:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>) kSecAttrKeyTypeRSA forKey:(__bridge <span class="hljs-keyword" style="color: rgb(0, 0, 136);">id</span>)kSecAttrKeyType]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Now fetch the SecKeyRef version of the key</span> SecKeyRef keyRef = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; status = SecItemCopyMatching((__bridge <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFDictionaryRef</span>)privateKey, (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFTypeRef</span> *)&keyRef); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(status != noErr){ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> keyRef; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)stripPrivateKeyHeader:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)d_key{ <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Skip ASN.1 private key header</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (d_key == <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">long</span> len = [d_key length]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!len) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span>(<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> *c_key = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> *)[d_key bytes]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idx = <span class="hljs-number" style="color: rgb(0, 102, 102);">22</span>; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//magic byte at offset 22</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (<span class="hljs-number" style="color: rgb(0, 102, 102);">0x04</span> != c_key[idx++]) <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//calculate length of the key</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> c_len = c_key[idx++]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> det = c_len & <span class="hljs-number" style="color: rgb(0, 102, 102);">0x80</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (!det) { c_len = c_len & <span class="hljs-number" style="color: rgb(0, 102, 102);">0x7f</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span> { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> byteCount = c_len & <span class="hljs-number" style="color: rgb(0, 102, 102);">0x7f</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (byteCount + idx > len) { <span class="hljs-comment" style="color: rgb(136, 0, 0);">//rsa length field longer than buffer</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> accum = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">unsigned</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">char</span> *ptr = &c_key[idx]; idx += byteCount; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">while</span> (byteCount) { accum = (accum << <span class="hljs-number" style="color: rgb(0, 102, 102);">8</span>) + *ptr; ptr++; byteCount--; } c_len = accum; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Now make a new NSData from this buffer</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> [d_key subdataWithRange:<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMakeRange</span>(idx, c_len)]; } + (<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)decryptData:(<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSData</span> *)data withKeyRef:(SecKeyRef) keyRef{ <span class="hljs-keyword" style="color: rgb(0, 0, 136);">const</span> uint8_t *srcbuf = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">const</span> uint8_t *)[data bytes]; size_t srclen = (size_t)data<span class="hljs-variable" style="color: rgb(102, 0, 102);">.length</span>; size_t block_size = SecKeyGetBlockSize(keyRef) * <span class="hljs-keyword" style="color: rgb(0, 0, 136);">sizeof</span>(uint8_t); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">UInt8</span> *outbuf = malloc(block_size); size_t src_block_size = block_size; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableData</span> *ret = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSMutableData</span> alloc] init]; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span>(<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idx=<span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; idx<srclen; idx+=src_block_size){ <span class="hljs-comment" style="color: rgb(136, 0, 0);">//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);</span> size_t data_len = srclen - idx; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span>(data_len > src_block_size){ data_len = src_block_size; } size_t outlen = block_size; OSStatus status = noErr; status = SecKeyDecrypt(keyRef, kSecPaddingNone, srcbuf + idx, data_len, outbuf, &outlen ); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> (status != <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>) { <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"SecKeyEncrypt fail. Error Code: %d"</span>, status); ret = <span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">break</span>; }<span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span>{ <span class="hljs-comment" style="color: rgb(136, 0, 0);">//the actual decrypted data is in the middle, locate it!</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idxFirstZero = -<span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> idxNextZero = (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span>)outlen; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">for</span> ( <span class="hljs-keyword" style="color: rgb(0, 0, 136);">int</span> i = <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span>; i < outlen; i++ ) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> ( outbuf[i] == <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span> ) { <span class="hljs-keyword" style="color: rgb(0, 0, 136);">if</span> ( idxFirstZero < <span class="hljs-number" style="color: rgb(0, 102, 102);">0</span> ) { idxFirstZero = i; } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">else</span> { idxNextZero = i; <span class="hljs-keyword" style="color: rgb(0, 0, 136);">break</span>; } } } [ret appendBytes:&outbuf[idxFirstZero+<span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>] length:idxNextZero-idxFirstZero-<span class="hljs-number" style="color: rgb(0, 102, 102);">1</span>]; } } free(outbuf); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">CFRelease</span>(keyRef); <span class="hljs-keyword" style="color: rgb(0, 0, 136);">return</span> ret; } <span class="hljs-comment" style="color: rgb(136, 0, 0);">/* END: Decryption with RSA private key */</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span></span></code>
4. 测试加密、解密
首先先测试使用.der
和.p12
秘钥文件进行加密、解密, 在ViewController.m
中进行测试, 代码如下:
<code class="objectivec"><span style="font-size: 18px;"><span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title">"ViewController.h"</span></span> <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title">"RSAEncryptor.h"</span></span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@interface</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">ViewController</span> ()</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@implementation</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">ViewController</span></span> - (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span>)viewDidLoad { [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">super</span> viewDidLoad]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//原始数据</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *originalString = <span class="hljs-string" style="color: rgb(0, 136, 0);">@"这是一段将要使用'.der'文件加密的字符串!"</span>; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//使用.der和.p12中的公钥私钥加密解密</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *public_key_path = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSBundle</span> mainBundle] pathForResource:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"public_key.der"</span> ofType:<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *private_key_path = [[<span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSBundle</span> mainBundle] pathForResource:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"private_key.p12"</span> ofType:<span class="hljs-literal" style="color: rgb(0, 102, 102);">nil</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *encryptStr = [RSAEncryptor encryptString:originalString publicKeyWithContentsOfFile:public_key_path]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"加密前:%@"</span>, originalString); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"加密后:%@"</span>, encryptStr); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"解密后:%@"</span>, [RSAEncryptor decryptString:encryptStr privateKeyWithContentsOfFile:private_key_path password:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"123456"</span>]); } - (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span>)didReceiveMemoryWarning { [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">super</span> didReceiveMemoryWarning]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Dispose of any resources that can be recreated.</span> } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span></span></code>
运行后, 输出信息如下:
![](https://i-blog.csdnimg.cn/blog_migrate/d3ae1eb36dd82b412fd7d2208b4416a6.webp?x-image-process=image/format,png)
可以看到已经可以成功加密、解密了.
下面接着测试使用秘钥字符串进行加密、解密, 那么秘钥字符串从哪里来? 可以来这里:http://web.chacuo.net/netrsakeypair, 这是一个在线生成RSA秘钥的网站, 生成公钥和秘钥后, 复制出来用于测试. 然后在ViewController.m
中使用RSAEntryptor.h
头文件中对应的加密方法进行加密, ViewController.m
中代码如下:
<code class="objectivec"><span style="font-size: 18px;"><span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title">"ViewController.h"</span></span> <span class="hljs-preprocessor" style="color: rgb(68, 68, 68);">#import <span class="hljs-title">"RSAEncryptor.h"</span></span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@interface</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">ViewController</span> ()</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span> <span class="hljs-class"><span class="hljs-keyword" style="color: rgb(0, 0, 136);">@implementation</span> <span class="hljs-title" style="color: rgb(102, 0, 102);">ViewController</span></span> - (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span>)viewDidLoad { [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">super</span> viewDidLoad]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//原始数据</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *originalString = <span class="hljs-string" style="color: rgb(0, 136, 0);">@"这是一段将要使用'秘钥字符串'进行加密的字符串!"</span>; <span class="hljs-comment" style="color: rgb(136, 0, 0);">//使用字符串格式的公钥私钥加密解密</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSString</span> *encryptStr = [RSAEncryptor encryptString:originalString publicKey:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTbZ6cNH9PgdF60aQKveLz3FTalyzHQwbp601y77SzmGHX3F5NoVUZbdK7UMdoCLK4FBziTewYD9DWvAErXZo9BFuI96bAop8wfl1VkZyyHTcznxNJFGSQd/B70/ExMgMBpEwkAAdyUqIjIdVGh1FQK/4acwS39YXwbS+IlHsPSQIDAQAB"</span>]; <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"加密前:%@"</span>, originalString); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"加密后:%@"</span>, encryptStr); <span class="hljs-built_in" style="color: rgb(102, 0, 102);">NSLog</span>(<span class="hljs-string" style="color: rgb(0, 136, 0);">@"解密后:%@"</span>, [RSAEncryptor decryptString:encryptStr privateKey:<span class="hljs-string" style="color: rgb(0, 136, 0);">@"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANNtnpw0f0+B0XrRpAq94vPcVNqXLMdDBunrTXLvtLOYYdfcXk2hVRlt0rtQx2gIsrgUHOJN7BgP0Na8AStdmj0EW4j3psCinzB+XVWRnLIdNzOfE0kUZJB38HvT8TEyAwGkTCQAB3JSoiMh1UaHUVAr/hpzBLf1hfBtL4iUew9JAgMBAAECgYA1tGeQmAkqofga8XtwuxEWDoaDS9k0+EKeUoXGxzqoT/GyiihuIafjILFhoUA1ndf/yCQaG973sbTDhtfpMwqFNQq13+JAownslTjWgr7Hwf7qplYW92R7CU0v7wFfjqm1t/2FKU9JkHfaHfb7qqESMIbO/VMjER9o4tEx58uXDQJBAO0O4lnWDVjr1gN02cqvxPOtTY6DgFbQDeaAZF8obb6XqvCqGW/AVms3Bh8nVlUwdQ2K/xte8tHxjW9FtBQTLd8CQQDkUncO35gAqUF9Bhsdzrs7nO1J3VjLrM0ITrepqjqtVEvdXZc+1/UrkWVaIigWAXjQCVfmQzScdbznhYXPz5fXAkEAgB3KMRkhL4yNpmKRjhw+ih+ASeRCCSj6Sjfbhx4XaakYZmbXxnChg+JB+bZNz06YBFC5nLZM7y/n61o1f5/56wJBALw+ZVzE6ly5L34114uG04W9x0HcFgau7MiJphFjgUdAtd/H9xfgE4odMRPUD3q9Me9LlMYK6MiKpfm4c2+3dzcCQQC8y37NPgpNEkd9smMwPpSEjPW41aMlfcKvP4Da3z7G5bGlmuICrva9YDAiaAyDGGCK8LxC8K6HpKrFgYrXkRtt"</span>]); } - (<span class="hljs-keyword" style="color: rgb(0, 0, 136);">void</span>)didReceiveMemoryWarning { [<span class="hljs-keyword" style="color: rgb(0, 0, 136);">super</span> didReceiveMemoryWarning]; <span class="hljs-comment" style="color: rgb(136, 0, 0);">// Dispose of any resources that can be recreated.</span> } <span class="hljs-keyword" style="color: rgb(0, 0, 136);">@end</span></span></code>
运行后, 输出信息如下:
![](https://i-blog.csdnimg.cn/blog_migrate/837aa426ffbf5ba09c62177ad43ae52d.webp?x-image-process=image/format,png)
可以看到,也成功加密、解密了.
至此, RSA加密演示完毕!
原文链接:http://www.jianshu.com/p/74a796ec5038