嘟噥嘟噥:最近接到一個任務(wù):在客戶端動態(tài)生成RSA密鑰對鞭执,然后向服務(wù)器發(fā)送這個密鑰對中的公鑰字符串,由服務(wù)器進(jìn)行公鑰加密芒粹,返回加密后的信息兄纺,再由客戶端使用私鑰進(jìn)行解密。我在網(wǎng)上查閱了大量的資料化漆,但是大多是利用公鑰私鑰文件估脆,或者直接接收RSA公私鑰字符串進(jìn)行加密解密,沒有生成并轉(zhuǎn)換成字符串座云,這里我們就介紹一下我是如何實現(xiàn)這個功能的疙赠,以備后用。
? ? ? ?我今天要介紹的RSA加密屬于非對稱加密朦拖。對于安全性來說顯然非對稱加密更優(yōu)于對稱加密圃阳。在使用中,甲方需要同時生成公開密鑰(公鑰)和私有密鑰(私鑰)璧帝,把其中的公鑰發(fā)送給乙方捍岳,乙方利用傳過來的私鑰,對發(fā)送文本進(jìn)行加密回傳給甲方,甲方接收到加密后的文本后用此前生成的私鑰進(jìn)行解密锣夹,從而得到加密前的文本页徐。但加密和解密花費時間長、速度慢晕城,它不適合于對文件加密而只適用于對少量數(shù)據(jù)進(jìn)行加密泞坦。
首先介紹利用終端生成公鑰私鑰
1、生成私鑰
openssl genrsa -out rsa_private_key.pem1024
2砖顷、將原始私鑰轉(zhuǎn)換為pkcs8格式
openssl pkcs8 -topk8 -inform PEM -inrsa_private_key.pem -outform PEM -nocrypt
3贰锁、根據(jù)私鑰生成公鑰
openssl rsa -in rsa_private_key.pem -pubout-out ras_public_key.pem
RSAPEM文件格式
1. PEM私鑰格式文件
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
2. PEM公鑰格式文件
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
3. PEM RSAPublicKey公鑰格式文件
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
回歸正題:我們開始實現(xiàn)生成密鑰字符串。在這里我們使用的是openssl框架來生成密鑰對滤蝠。
頭文件中引入
#import <openssl/rsa.h>
#import <openssl/pem.h>
1,生成密鑰對
/*產(chǎn)生RSA密鑰*/
RSA*rsa =NULL;
rsa =RSA_new();
//產(chǎn)生一個模為num位的密鑰對豌熄,e為公開的加密指數(shù),一般為65537(0x10001)
rsa =RSA_generate_key(1024,0x10001,NULL,NULL);
? ? ? ?這里需要說明一下物咳,加密長度是1024位锣险。加密長度是指理論上最大允許”被加密的信息“長度的限制,也就是明文的長度限制览闰。隨著這個參數(shù)的增大(比方說2048)芯肤,允許的明文長度也會增加,但同時也會造成計算復(fù)雜度的極速增長压鉴。一般推薦的長度就是1024位(128字節(jié))崖咨。
? ? ? ?這種算法非常可靠油吭,密鑰越長击蹲,它就越難破解。根據(jù)已經(jīng)披露的文獻(xiàn)婉宰,目前被破解的最長RSA密鑰是768個二進(jìn)制位歌豺。也就是說,長度超過768位的密鑰心包,還無法破解(至少沒人公開宣布)类咧。因此可以認(rèn)為,1024位的RSA密鑰基本安全蟹腾,2048位的密鑰極其安全痕惋。
? ? ? ?由于我并沒有在框架中找到方法轉(zhuǎn)換出密鑰字符串,所以這里用了個比較笨拙的方法岭佳,將公鑰私鑰保存為txt文件血巍,然后將這個txt文件讀出萧锉,讀出后就是需要的字符串了珊随。
上方加粗函數(shù)雖然已經(jīng)過時,但是目前還可以用,下方加粗部分是替代方法
BIGNUM*bne =BN_new();
unsignedinte =RSA_3;
intresult =BN_set_word(bne, e);
result =RSA_generate_key_ex(rsa,1024, bne,NULL);
rsa就是得到的密鑰對
//路徑
NSString*documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
/*提取公鑰字符串*/
//最終存儲的地方叶洞,所以需要創(chuàng)建一個路徑去存儲字符串
NSString*pubPath = [documentsPathstringByAppendingPathComponent:@"PubFile.txt"];
FILE* pubWrite =NULL;
pubWrite =fopen([pubPathUTF8String],"wb");
if(pubWrite ==NULL)
NSLog(@"Read Filed.");
else
{
PEM_write_RSA_PUBKEY(pubWrite,rsa);
fclose(pubWrite);
}
? ? ? ?拿出字符串之后對字符串進(jìn)行處理鲫凶,這樣就得到了我們需要的字符串了。
NSString*str=[NSStringstringWithContentsOfFile:pubPathencoding:NSUTF8StringEncodingerror:nil];
str = [strstringByReplacingOccurrencesOfString:@"-----BEGIN
PUBLIC KEY-----"withString:@""];
str = [strstringByReplacingOccurrencesOfString:@"-----END
PUBLIC KEY-----"withString:@""];
str = [strstringByReplacingOccurrencesOfString:@"\n"withString:@""];
/*提取私鑰字符串*/
NSString*priPath =
[documentsPathstringByAppendingPathComponent:@"PriFile.txt"];
FILE*priWtire =NULL;
priWtire =fopen([priPathUTF8String],"wb");
EVP_PKEY*pkey =NULL;
if(priWtire ==NULL) {
NSLog(@"Read
Filed.");
}else{
//函數(shù)使用PKCS#8標(biāo)準(zhǔn)保存EVP_PKEY里面的私鑰到文件或者BIO中衩辟,并采用PKCS#5
//v2.0的標(biāo)準(zhǔn)加密私鑰螟炫。enc參數(shù)定義了使用的加密算法。跟其他PEM的IO函數(shù)不一樣的是艺晴,本函數(shù)的加密是基于PKCS#8層次上的昼钻,而不是基于PEM信息字段的,所以這兩個函數(shù)也是單獨實現(xiàn)的函數(shù)封寞,而不是宏定義函數(shù)然评。如果enc參數(shù)為NULL,那么就不會執(zhí)行加密操作狈究,只是使用PKCS#8私鑰 信息結(jié)構(gòu)碗淌。成功執(zhí)行返回大于0的數(shù),否則返回0抖锥。
pkey =EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(priWtire, pkey,NULL,NULL,0,0,NULL);
fclose(priWtire);
}
NSString*priStr=[NSStringstringWithContentsOfFile:priPathencoding:NSUTF8StringEncodingerror:nil];
priStr = [priStrstringByReplacingOccurrencesOfString:@"-----BEGIN
PRIVATE KEY-----"withString:@""];
priStr = [priStrstringByReplacingOccurrencesOfString:@"-----END
PRIVATE KEY-----"withString:@""];
priStr = [priStrstringByReplacingOccurrencesOfString:@"\n"withString:@""];
得到私鑰字符串亿眠。
以下是問題記錄:
1.利用PEM_write_RSA_PUBKEY函數(shù)保存密鑰后,無法獲得密鑰磅废,原因是我在設(shè)置文件的時候纳像,參考網(wǎng)上的資料,寫成了文件名稱还蹲,獲取的時候也是利用框架中的函數(shù)獲取到的RSA爹耗,還是沒有轉(zhuǎn)換成字符串。所以我將設(shè)置文件的地方谜喊,寫入了文件路徑潭兽,然后我再用自己的方式讀取這個txt文件,這樣就得到了我想要的字符串了斗遏。
2.保存密鑰的時候山卦,開始的時候得到的公鑰私鑰都是不能正確加密解密的,原因是我在保存密鑰文件的時候诵次,選錯了文件的格式账蓉,這里有兩個函數(shù)很容易讓人混淆:
PEM_write_RSAPublicKey(<#FILE *fp#>,<#const RSA *x#>)
由這個函數(shù)得到的文件是PRM RSAPublicKey公鑰格式文件,而我們需要的文件是PEM公鑰格式文件逾一,所以要看好函數(shù)指定的文件格式铸本。利用PEM_write_RSA_PUBKEY函數(shù)。
PEM_write_RSAPrivateKey(<#FILE *fp#>, <#RSA *x#>, <#constEVP_CIPHER *enc#>, <#unsigned char *kstr#>, <#int klen#>,<#pem_password_cb *cb#>, <#void *u#>)
通過這個函數(shù)我們雖然可以得到私鑰文件遵堵,但是卻是PKCS1格式的箱玷,但是我需要的是PKCS8格式的怨规。所以需要改用這個函數(shù)PEM_write_PKCS8PrivateKey蓄髓。
選擇了正確的文件格式椰棘,生成的公鑰私鑰就可以使用了。
這篇博文中有關(guān)于文件格式的大體介紹
http://blog.csdn.net/tuhuolong/article/details/42778945
? ? ? ?這篇文章并沒有對原理進(jìn)行剖析暇昂,只是說明了一下使用方法舶得,而且使用方法不是很好掰烟,我想框架中應(yīng)該也有可以實現(xiàn)的方法,但是目前還沒有找到沐批,如果有哪位朋友找到了纫骑,一定要記得私信告訴我,謝謝九孩。
不知道怎么傳文件 貼一份源碼吧 (源碼中包括生成動態(tài)key 以及加密解密可能會有多余的方法惧磺,因為是在別人的源碼基礎(chǔ)上修改的)
需要引入:
libcrypto.a
libssl.a
以及openssl框架(我直接從支付寶的框架里搞來的)
//
//RYTRSAEncryptor.h
//SMSCodeTest
//Created by timmy on 16/10/19.
//Copyright ? 2016年 timmy. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <openssl/rsa.h>
@interface RYTRSAEncryptor : NSObject
+ (void)keyWith:(void(^)(NSString *pubKey, NSString *priKey))block;
/**
*加密方法
*
*@param str需要加密的字符串
*@param pubKey公鑰字符串
*/
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
+ (SecKeyRef)addPublicKey:(NSString *)key;
/**
*解密方法
*
*@param str需要解密的字符串
*@param privKey私鑰字符串
*/
+ (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;
+ (SecKeyRef)addPrivateKey:(NSString *)key;
@end
//RYTRSAEncryptor.m
//SMSCodeTest
//Created by timmy on 16/10/19.
//Copyright ? 2016年 timmy. All rights reserved.
#import "RYTRSAEncryptor.h"
#import <Security/Security.h>
#import <openssl/rsa.h>
#import <openssl/pem.h>
#import "RYTBase64.h"
@implementation ?RYTRSAEncryptor
staticNSString *base64_encode_data(NSData *data){
data = [data base64EncodedDataWithOptions:0];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
returnret;
}
staticNSData *base64_decode(NSString *str){
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
returndata;
}
#pragma mark -生成密鑰
/* START: creat keys */
+ (void)keyWith:(void(^)(NSString *pubKey, NSString *priKey))block {
/* 產(chǎn)生RSA密鑰 */
RSA *rsa =NULL;
rsa = RSA_new();
//產(chǎn)生一個模為num位的密鑰對,e為公開的加密指數(shù)捻撑,一般為65537(0x10001)
rsa = RSA_generate_key(1024,0x10001,NULL,NULL);
// 路徑
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0];
/* 提取公鑰字符串 */
// 最終存儲的地方磨隘,所以需要創(chuàng)建一個路徑去存儲字符串
NSString *pubPath = [documentsPath stringByAppendingPathComponent:@"PubFile.txt"];
FILE* pubWrite =NULL;
pubWrite = fopen([pubPath UTF8String],"wb");
if(pubWrite ==NULL)
NSLog(@"Read Filed.");
else
{
PEM_write_RSA_PUBKEY(pubWrite,rsa);
fclose(pubWrite);
}
NSString *str=[NSString stringWithContentsOfFile:pubPath encoding:NSUTF8StringEncoding error:nil];
str = [str stringByReplacingOccurrencesOfString:@"-----BEGIN PUBLIC KEY-----"withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"-----END PUBLIC KEY-----"withString:@""];
str = [str stringByReplacingOccurrencesOfString:@"\n"withString:@""];
/*提取私鑰字符串*/
NSString *priPath = [documentsPath stringByAppendingPathComponent:@"PriFile.txt"];
FILE *priWtire =NULL;
priWtire = fopen([priPath UTF8String],"wb");
EVP_PKEY *pkey =NULL;
if(priWtire ==NULL) {
NSLog(@"Read Filed.");
}else{
//函數(shù)使用PKCS#8標(biāo)準(zhǔn)保存EVP_PKEY里面的私鑰到文件或者BIO中,并采用PKCS#5
//v2.0的標(biāo)準(zhǔn)加密私鑰顾患。enc參數(shù)定義了使用的加密算法番捂。跟其他PEM的IO函數(shù)不一樣的是,本函數(shù)的加密是基于PKCS#8層次上的江解,而不是基于PEM信息字段的设预,所以這兩個函數(shù)也是單獨實現(xiàn)的函數(shù),而不是宏定義函數(shù)犁河。如果enc參數(shù)為NULL鳖枕,那么就不會執(zhí)行加密操作,只是使用PKCS#8私鑰 信息結(jié)構(gòu)桨螺。成功執(zhí)行返回大于0 的數(shù)宾符,否則返回0。
pkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(pkey, rsa);
PEM_write_PKCS8PrivateKey(priWtire, pkey,NULL,NULL,0,0,NULL);
fclose(priWtire);
}
NSString *priStr=[NSString stringWithContentsOfFile:priPath encoding:NSUTF8StringEncoding error:nil];
priStr = [priStr stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----"withString:@""];
priStr = [priStr stringByReplacingOccurrencesOfString:@"-----END PRIVATE KEY-----"withString:@""];
priStr = [priStr stringByReplacingOccurrencesOfString:@"\n"withString:@""];
block(str,priStr);
}
#pragma mark -使用公鑰字符串加密
/* START: Encryption with RSA public key */
//使用公鑰字符串加密(PKCS8格式)
+ (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{
NSData *data = [selfencryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
NSString *ret = base64_encode_data(data);
returnret;
}
+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{
if(!data || !pubKey){
returnnil;
}
SecKeyRef keyRef = [selfaddPublicKey:pubKey];
if(!keyRef){
returnnil;
}
return[selfencryptData:data withKeyRef:keyRef];
}
//構(gòu)建公鑰(PKCS8格式)
+ (SecKeyRef)addPublicKey:(NSString *)key {
NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" "withString:@""];
//key經(jīng)過base64編碼 解碼
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 = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
[publicKey setObject:(__bridgeid) kSecClassKey forKey:(__bridgeid)kSecClass];
[publicKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];
[publicKey setObject:d_tag forKey:(__bridgeid)kSecAttrApplicationTag];
SecItemDelete((__bridgeCFDictionaryRef)publicKey);
// Add persistent version of the key to system keychain
[publicKey setObject:data forKey:(__bridgeid)kSecValueData];
[publicKey setObject:(__bridgeid) kSecAttrKeyClassPublic forKey:(__bridgeid)
kSecAttrKeyClass];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)
kSecReturnPersistentRef];
CFTypeRef persistKey =nil;
OSStatus status = SecItemAdd((__bridgeCFDictionaryRef)publicKey, &persistKey);
if(persistKey !=nil){
CFRelease(persistKey);
}
if((status != noErr) && (status != errSecDuplicateItem)) {
returnnil;
}
[publicKey removeObjectForKey:(__bridgeid)kSecValueData];
[publicKey removeObjectForKey:(__bridgeid)kSecReturnPersistentRef];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];
[publicKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef =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_key length];
if(!len)return(nil);
unsignedchar*c_key = (unsignedchar*)[d_key bytes];
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([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}
+ (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
constuint8_t *srcbuf = (constuint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) *sizeof(uint8_t);
void*outbuf = malloc(block_size);
size_t src_block_size = block_size -11;
NSMutableData *ret = [[NSMutableData alloc] init];
for(intidx=0; idx
//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(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
);
if(status !=0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
ret =nil;
break;
}else{
[ret appendBytes:outbuf length: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 = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
data = [selfdecryptData:data privateKey:privKey];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
returnret;
}
+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{
if(!data || !privKey){
returnnil;
}
SecKeyRef keyRef = [selfaddPrivateKey:privKey];
if(!keyRef){
returnnil;
}
return[selfdecryptData:data withKeyRef:keyRef];
}
//(PKCS8格式)
+ (SecKeyRef)addPrivateKey:(NSString *)key{
NSRange spos = [key rangeOfString:@"-----BEGIN PRIVATE KEY-----"];
NSRange epos = [key rangeOfString:@"-----END PRIVATE KEY-----"];
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t"withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" "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 = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
[privateKey setObject:(__bridgeid) kSecClassKey forKey:(__bridgeid)kSecClass];
[privateKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];
[privateKey setObject:d_tag forKey:(__bridgeid)kSecAttrApplicationTag];
SecItemDelete((__bridgeCFDictionaryRef)privateKey);
// Add persistent version of the key to system keychain
[privateKey setObject:data forKey:(__bridgeid)kSecValueData];
[privateKey setObject:(__bridgeid) kSecAttrKeyClassPrivate forKey:(__bridgeid)
kSecAttrKeyClass];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)
kSecReturnPersistentRef];
CFTypeRef persistKey =nil;
OSStatus status = SecItemAdd((__bridgeCFDictionaryRef)privateKey, &persistKey);
if(persistKey !=nil){
CFRelease(persistKey);
}
if((status != noErr) && (status != errSecDuplicateItem)) {
returnnil;
}
[privateKey removeObjectForKey:(__bridgeid)kSecValueData];
[privateKey removeObjectForKey:(__bridgeid)kSecReturnPersistentRef];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];
[privateKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef =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_key length];
if(!len)return(nil);
unsignedchar*c_key = (unsignedchar*)[d_key bytes];
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_key subdataWithRange:NSMakeRange(idx, c_len)];
}
+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
constuint8_t *srcbuf = (constuint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) *sizeof(uint8_t);
UInt8 *outbuf = malloc(block_size);
size_t src_block_size = block_size;
NSMutableData *ret = [[NSMutableData alloc] init];
for(intidx=0; idx
size_t data_len = srclen - idx;
if(data_len > src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyDecrypt(keyRef,
kSecPaddingPKCS1,
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;
}
}
}
[ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
}
}
free(outbuf);
CFRelease(keyRef);
returnret;
}
@end
比起碼源碼灭翔,還是放項目比較直接魏烫,這個是項目地址,有興趣的同學(xué)可以看看肝箱。
https://git.oschina.net/euagore/smscodeframework.git