RSA加密

在iOS中使用RSA加密解密,需要用到.der和.p12后缀格式的文件,其中.der格式的文件存放的是公钥(Public key)用于加密,.p12格式的文件存放的是私钥(Private key)用于解密. 首先需要先生成这些文件,然后再将文件导入工程使用,不多说,开始做!

一、使用openssl生成所需秘钥文件

生成环境是在mac系统下,使用openssl进行生成,首先打开终端,按下面这些步骤依次来做:

1. 生成模长为1024bit的私钥文件private_key.pem

openssl genrsa -out private.pem 1024

2. 生成证书请求文件rsaCertReq.csr

openssl req -new -key private_key.pem -out rsaCerReq.csr

注意:这一步会提示输入国家、省份、mail等信息,可以根据实际情况填写,或者全部不用填写,直接全部敲回车.

3. 生成证书rsaCert.crt,并设置有效时间为10年

openssl x509 -req -days 3650 -in rsaCerReq.csr -signkey private_key.pem -out rsaCert.crt

4. 生成供iOS使用的公钥文件public_key.der

openssl x509 -outform der -inrsaCert.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 -inprivate_key.pem -out pkcs8_private_key.pem -nocrypt

全部执行成功后,会生成如下文件,其中public_key.der和private_key.p12就是iOS需要用到的文件,如下图:

RSA加密_第1张图片

生成的文件

二、将文件导入工程使用

1.新建工程, 并导入Security.framework框架, 如下图:

RSA加密_第2张图片

新建工程并添加框架

2.导入秘钥文件

导入.der和.p12格式的秘钥文件, 如下图:

RSA加密_第3张图片

导入秘钥文件

3.新建用于加密、解密的类RSAEncryptor, 并实现相关方法

新建RSAEncryptor类, 如下图:

RSA加密_第4张图片

新建用于加密解密的类

下面开始上代码, 可以直接复制过去用:

RSAEncryptor.h代码如下:

//

//RSAEncryptor.h

//毛票食堂

//

//Created by Apple on 17/2/11.

//Copyright © 2017年Pandora. All rights reserved.

//

#import

@interfaceRSAEncryptor :NSObject

/**

*加密方法

*

*@param str需要加密的字符串

*@param path'.der'格式的公钥文件路径

*/

+ (NSString*)encryptString:(NSString*)str publicKeyWithContentsOfFile:(NSString*)path;

/**

*解密方法

*

*@param str需要解密的字符串

*@param path'.p12'格式的私钥文件路径

*@param password私钥文件密码

*/

+ (NSString*)decryptString:(NSString*)str privateKeyWithContentsOfFile:(NSString*)path password:(NSString*)password;

/**

*加密方法

*

*@param str需要加密的字符串

*@param pubKey公钥字符串

*/

+ (NSString*)encryptString:(NSString*)str publicKey:(NSString*)pubKey;

/**

*解密方法

*

*@param str需要解密的字符串

*@param privKey私钥字符串

*/

+ (NSString*)decryptString:(NSString*)str privateKey:(NSString*)privKey;

@end

//

//RSAEncryptor.m

//毛票食堂

//

//Created by Apple on 17/2/11.

//Copyright © 2017年Pandora. All rights reserved.

//

#import"RSAEncryptor.h"

//RSAEncryptor.m代码如下:

#import"RSAEncryptor.h"

#import

@implementationRSAEncryptor

staticNSString*base64_encode_data(NSData*data){

data = [database64EncodedDataWithOptions:0];

NSString*ret = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

returnret;

}

staticNSData*base64_decode(NSString*str){

NSData*data = [[NSDataalloc]initWithBase64EncodedString:stroptions:NSDataBase64DecodingIgnoreUnknownCharacters];

returndata;

}

#pragma mark -使用'.der'公钥文件加密

//加密

+ (NSString*)encryptString:(NSString*)str publicKeyWithContentsOfFile:(NSString*)path{

if(!str || !path)returnnil;

return[selfencryptString:strpublicKeyRef:[selfgetPublicKeyRefWithContentsOfFile:path]];

}

//获取公钥

+ (SecKeyRef)getPublicKeyRefWithContentsOfFile:(NSString*)filePath{

NSData*certData = [NSDatadataWithContentsOfFile:filePath];

if(!certData) {

returnnil;

}

SecCertificateRefcert =SecCertificateCreateWithData(NULL, (CFDataRef)certData);

SecKeyRefkey =NULL;

SecTrustReftrust =NULL;

SecPolicyRefpolicy =NULL;

if(cert !=NULL) {

policy =SecPolicyCreateBasicX509();

if(policy) {

if(SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) ==noErr) {

SecTrustResultTyperesult;

if(SecTrustEvaluate(trust, &result) ==noErr) {

key =SecTrustCopyPublicKey(trust);

}

}

}

}

if(policy)CFRelease(policy);

if(trust)CFRelease(trust);

if(cert)CFRelease(cert);

returnkey;

}

+ (NSString*)encryptString:(NSString*)str publicKeyRef:(SecKeyRef)publicKeyRef{

if(![strdataUsingEncoding:NSUTF8StringEncoding]){

returnnil;

}

if(!publicKeyRef){

returnnil;

}

NSData*data = [selfencryptData:[strdataUsingEncoding:NSUTF8StringEncoding]withKeyRef:publicKeyRef];

NSString*ret =base64_encode_data(data);

returnret;

}

#pragma mark -使用'.12'私钥文件解密

//解密

+ (NSString*)decryptString:(NSString*)str privateKeyWithContentsOfFile:(NSString*)path password:(NSString*)password{

if(!str || !path)returnnil;

if(!password) password =@"";

return[selfdecryptString:strprivateKeyRef:[selfgetPrivateKeyRefWithContentsOfFile:pathpassword:password]];

}

//获取私钥

+ (SecKeyRef)getPrivateKeyRefWithContentsOfFile:(NSString*)filePath password:(NSString*)password{

NSData*p12Data = [NSDatadataWithContentsOfFile:filePath];

if(!p12Data) {

returnnil;

}

SecKeyRefprivateKeyRef =NULL;

NSMutableDictionary* options = [[NSMutableDictionaryalloc]init];

[optionssetObject: passwordforKey:(__bridgeid)kSecImportExportPassphrase];

CFArrayRefitems =CFArrayCreate(NULL,0,0,NULL);

OSStatussecurityError =SecPKCS12Import((__bridgeCFDataRef) p12Data, (__bridgeCFDictionaryRef)options, &items);

if(securityError ==noErr&&CFArrayGetCount(items) >0) {

CFDictionaryRefidentityDict =CFArrayGetValueAtIndex(items,0);

SecIdentityRefidentityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict,kSecImportItemIdentity);

securityError =SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);

if(securityError !=noErr) {

privateKeyRef =NULL;

}

}

CFRelease(items);

returnprivateKeyRef;

}

+ (NSString*)decryptString:(NSString*)str privateKeyRef:(SecKeyRef)privKeyRef{

NSData*data = [[NSDataalloc]initWithBase64EncodedString:stroptions:NSDataBase64DecodingIgnoreUnknownCharacters];

if(!privKeyRef) {

returnnil;

}

data = [selfdecryptData:datawithKeyRef:privKeyRef];

NSString*ret = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

returnret;

}

#pragma mark -使用公钥字符串加密

/* START: Encryption with RSA public key */

//使用公钥字符串加密

+ (NSString*)encryptString:(NSString*)str publicKey:(NSString*)pubKey{

NSData*data = [selfencryptData:[strdataUsingEncoding:NSUTF8StringEncoding]publicKey:pubKey];

NSString*ret =base64_encode_data(data);

returnret;

}

+ (NSData*)encryptData:(NSData*)data publicKey:(NSString*)pubKey{

if(!data || !pubKey){

returnnil;

}

SecKeyRefkeyRef = [selfaddPublicKey:pubKey];

if(!keyRef){

returnnil;

}

return[selfencryptData:datawithKeyRef:keyRef];

}

+ (SecKeyRef)addPublicKey:(NSString*)key{

NSRangespos = [keyrangeOfString:@"-----BEGIN PUBLIC KEY-----"];

NSRangeepos = [keyrangeOfString:@"-----END PUBLIC KEY-----"];

if(spos.location!=NSNotFound&& epos.location!=NSNotFound){

NSUIntegers = spos.location+ spos.length;

NSUIntegere = epos.location;

NSRangerange =NSMakeRange(s, e-s);

key = [keysubstringWithRange:range];

}

key = [keystringByReplacingOccurrencesOfString:@"\r"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@"\n"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@"\t"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@" "withString:@""];

// This will be base64 encoded, decode it.

NSData*data =base64_decode(key);

data = [selfstripPublicKeyHeader:data];

if(!data){

returnnil;

}

//a tag to read/write keychain storage

NSString*tag =@"RSAUtil_PubKey";

NSData*d_tag = [NSDatadataWithBytes:[tagUTF8String]length:[taglength]];

// Delete any old lingering key with the same tag

NSMutableDictionary*publicKey = [[NSMutableDictionaryalloc]init];

[publicKeysetObject:(__bridgeid)kSecClassKeyforKey:(__bridgeid)kSecClass];

[publicKeysetObject:(__bridgeid)kSecAttrKeyTypeRSAforKey:(__bridgeid)kSecAttrKeyType];

[publicKeysetObject:d_tagforKey:(__bridgeid)kSecAttrApplicationTag];

SecItemDelete((__bridgeCFDictionaryRef)publicKey);

// Add persistent version of the key to system keychain

[publicKeysetObject:dataforKey:(__bridgeid)kSecValueData];

[publicKeysetObject:(__bridgeid)kSecAttrKeyClassPublicforKey:(__bridgeid)

kSecAttrKeyClass];

[publicKeysetObject:[NSNumbernumberWithBool:YES]forKey:(__bridgeid)

kSecReturnPersistentRef];

CFTypeRefpersistKey =nil;

OSStatusstatus =SecItemAdd((__bridgeCFDictionaryRef)publicKey, &persistKey);

if(persistKey !=nil){

CFRelease(persistKey);

}

if((status !=noErr) && (status !=errSecDuplicateItem)) {

returnnil;

}

[publicKeyremoveObjectForKey:(__bridgeid)kSecValueData];

[publicKeyremoveObjectForKey:(__bridgeid)kSecReturnPersistentRef];

[publicKeysetObject:[NSNumbernumberWithBool:YES]forKey:(__bridgeid)kSecReturnRef];

[publicKeysetObject:(__bridgeid)kSecAttrKeyTypeRSAforKey:(__bridgeid)kSecAttrKeyType];

// Now fetch the SecKeyRef version of the key

SecKeyRefkeyRef =nil;

status =SecItemCopyMatching((__bridgeCFDictionaryRef)publicKey, (CFTypeRef*)&keyRef);

if(status !=noErr){

returnnil;

}

returnkeyRef;

}

+ (NSData*)stripPublicKeyHeader:(NSData*)d_key{

// Skip ASN.1 public key header

if(d_key ==nil)return(nil);

unsignedlonglen = [d_keylength];

if(!len)return(nil);

unsignedchar*c_key = (unsignedchar*)[d_keybytes];

unsignedintidx=0;

if(c_key[idx++] !=0x30)return(nil);

if(c_key[idx] >0x80) idx += c_key[idx] -0x80+1;

elseidx++;

// PKCS #1 rsaEncryption szOID_RSA_RSA

staticunsignedcharseqiod[] =

{0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,

0x01,0x05,0x00};

if(memcmp(&c_key[idx], seqiod,15))return(nil);

idx +=15;

if(c_key[idx++] !=0x03)return(nil);

if(c_key[idx] >0x80) idx += c_key[idx] -0x80+1;

elseidx++;

if(c_key[idx++] !='\0')return(nil);

// Now make a new NSData from this buffer

return([NSDatadataWithBytes:&c_key[idx]length:len - idx]);

}

+ (NSData*)encryptData:(NSData*)data withKeyRef:(SecKeyRef) keyRef{

constuint8_t*srcbuf = (constuint8_t*)[databytes];

size_tsrclen = (size_t)data.length;

size_tblock_size =SecKeyGetBlockSize(keyRef) *sizeof(uint8_t);

void*outbuf =malloc(block_size);

size_tsrc_block_size = block_size -11;

NSMutableData*ret = [[NSMutableDataalloc]init];

for(intidx=0; idx

//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);

size_tdata_len = srclen - idx;

if(data_len > src_block_size){

data_len = src_block_size;

}

size_toutlen = block_size;

OSStatusstatus =noErr;

status =SecKeyEncrypt(keyRef,

kSecPaddingPKCS1,

srcbuf + idx,

data_len,

outbuf,

&outlen

);

if(status !=0) {

NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);

ret =nil;

break;

}else{

[retappendBytes:outbuflength:outlen];

}

}

free(outbuf);

CFRelease(keyRef);

returnret;

}

/* END: Encryption with RSA public key */

#pragma mark -使用私钥字符串解密

/* START: Decryption with RSA private key */

//使用私钥字符串解密

+ (NSString*)decryptString:(NSString*)str privateKey:(NSString*)privKey{

if(!str)returnnil;

NSData*data = [[NSDataalloc]initWithBase64EncodedString:stroptions:NSDataBase64DecodingIgnoreUnknownCharacters];

data = [selfdecryptData:dataprivateKey:privKey];

NSString*ret = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];

returnret;

}

+ (NSData*)decryptData:(NSData*)data privateKey:(NSString*)privKey{

if(!data || !privKey){

returnnil;

}

SecKeyRefkeyRef = [selfaddPrivateKey:privKey];

if(!keyRef){

returnnil;

}

return[selfdecryptData:datawithKeyRef:keyRef];

}

+ (SecKeyRef)addPrivateKey:(NSString*)key{

NSRangespos = [keyrangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];

NSRangeepos = [keyrangeOfString:@"-----END RSA PRIVATE KEY-----"];

if(spos.location!=NSNotFound&& epos.location!=NSNotFound){

NSUIntegers = spos.location+ spos.length;

NSUIntegere = epos.location;

NSRangerange =NSMakeRange(s, e-s);

key = [keysubstringWithRange:range];

}

key = [keystringByReplacingOccurrencesOfString:@"\r"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@"\n"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@"\t"withString:@""];

key = [keystringByReplacingOccurrencesOfString:@" "withString:@""];

// This will be base64 encoded, decode it.

NSData*data =base64_decode(key);

data = [selfstripPrivateKeyHeader:data];

if(!data){

returnnil;

}

//a tag to read/write keychain storage

NSString*tag =@"RSAUtil_PrivKey";

NSData*d_tag = [NSDatadataWithBytes:[tagUTF8String]length:[taglength]];

// Delete any old lingering key with the same tag

NSMutableDictionary*privateKey = [[NSMutableDictionaryalloc]init];

[privateKeysetObject:(__bridgeid)kSecClassKeyforKey:(__bridgeid)kSecClass];

[privateKeysetObject:(__bridgeid)kSecAttrKeyTypeRSAforKey:(__bridgeid)kSecAttrKeyType];

[privateKeysetObject:d_tagforKey:(__bridgeid)kSecAttrApplicationTag];

SecItemDelete((__bridgeCFDictionaryRef)privateKey);

// Add persistent version of the key to system keychain

[privateKeysetObject:dataforKey:(__bridgeid)kSecValueData];

[privateKeysetObject:(__bridgeid)kSecAttrKeyClassPrivateforKey:(__bridgeid)

kSecAttrKeyClass];

[privateKeysetObject:[NSNumbernumberWithBool:YES]forKey:(__bridgeid)

kSecReturnPersistentRef];

CFTypeRefpersistKey =nil;

OSStatusstatus =SecItemAdd((__bridgeCFDictionaryRef)privateKey, &persistKey);

if(persistKey !=nil){

CFRelease(persistKey);

}

if((status !=noErr) && (status !=errSecDuplicateItem)) {

returnnil;

}

[privateKeyremoveObjectForKey:(__bridgeid)kSecValueData];

[privateKeyremoveObjectForKey:(__bridgeid)kSecReturnPersistentRef];

[privateKeysetObject:[NSNumbernumberWithBool:YES]forKey:(__bridgeid)kSecReturnRef];

[privateKeysetObject:(__bridgeid)kSecAttrKeyTypeRSAforKey:(__bridgeid)kSecAttrKeyType];

// Now fetch the SecKeyRef version of the key

SecKeyRefkeyRef =nil;

status =SecItemCopyMatching((__bridgeCFDictionaryRef)privateKey, (CFTypeRef*)&keyRef);

if(status !=noErr){

returnnil;

}

returnkeyRef;

}

+ (NSData*)stripPrivateKeyHeader:(NSData*)d_key{

// Skip ASN.1 private key header

if(d_key ==nil)return(nil);

unsignedlonglen = [d_keylength];

if(!len)return(nil);

unsignedchar*c_key = (unsignedchar*)[d_keybytes];

unsignedintidx=22;//magic byte at offset 22

if(0x04!= c_key[idx++])returnnil;

//calculate length of the key

unsignedintc_len = c_key[idx++];

intdet = c_len &0x80;

if(!det) {

c_len = c_len &0x7f;

}else{

intbyteCount = c_len &0x7f;

if(byteCount + idx > len) {

//rsa length field longer than buffer

returnnil;

}

unsignedintaccum =0;

unsignedchar*ptr = &c_key[idx];

idx += byteCount;

while(byteCount) {

accum = (accum <<8) + *ptr;

ptr++;

byteCount--;

}

c_len = accum;

}

// Now make a new NSData from this buffer

return[d_keysubdataWithRange:NSMakeRange(idx, c_len)];

}

+ (NSData*)decryptData:(NSData*)data withKeyRef:(SecKeyRef) keyRef{

constuint8_t*srcbuf = (constuint8_t*)[databytes];

size_tsrclen = (size_t)data.length;

size_tblock_size =SecKeyGetBlockSize(keyRef) *sizeof(uint8_t);

UInt8*outbuf =malloc(block_size);

size_tsrc_block_size = block_size;

NSMutableData*ret = [[NSMutableDataalloc]init];

for(intidx=0; idx

//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);

size_tdata_len = srclen - idx;

if(data_len > src_block_size){

data_len = src_block_size;

}

size_toutlen = block_size;

OSStatusstatus =noErr;

status =SecKeyDecrypt(keyRef,

kSecPaddingNone,

srcbuf + idx,

data_len,

outbuf,

&outlen

);

if(status !=0) {

NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);

ret =nil;

break;

}else{

//the actual decrypted data is in the middle, locate it!

intidxFirstZero = -1;

intidxNextZero = (int)outlen;

for(inti =0; i < outlen; i++ ) {

if( outbuf[i] ==0) {

if( idxFirstZero <0) {

idxFirstZero = i;

}else{

idxNextZero = i;

break;

}

}

}

[retappendBytes:&outbuf[idxFirstZero+1]length:idxNextZero-idxFirstZero-1];

}

}

free(outbuf);

CFRelease(keyRef);

returnret;

}

/* END: Decryption with RSA private key */

@end

你可能感兴趣的:(RSA加密)