11

#import"RSAEncryptor.h"#import@implementationRSAEncryptorstaticNSString*base64_encode_data(NSData*data){    data = [data base64EncodedDataWithOptions:0];NSString*ret = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];returnret;}staticNSData*base64_decode(NSString*str){NSData*data = [[NSDataalloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];returndata;}#pragma mark - 使用'.der'公钥文件加密//加密+ (NSString*)encryptString:(NSString*)str publicKeyWithContentsOfFile:(NSString*)path{if(!str || !path)returnnil;return[selfencryptString:str publicKeyRef:[selfgetPublicKeyRefWithContentsOfFile:path]];}//获取公钥+ (SecKeyRef)getPublicKeyRefWithContentsOfFile:(NSString*)filePath{NSData*certData = [NSDatadataWithContentsOfFile:filePath];if(!certData) {returnnil;    }    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);    SecKeyRef key =NULL;    SecTrustRef trust =NULL;    SecPolicyRef policy =NULL;if(cert !=NULL) {        policy = SecPolicyCreateBasicX509();if(policy) {if(SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {                SecTrustResultType result;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(![str dataUsingEncoding:NSUTF8StringEncoding]){returnnil;    }if(!publicKeyRef){returnnil;    }NSData*data = [selfencryptData:[str dataUsingEncoding: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:str privateKeyRef:[selfgetPrivateKeyRefWithContentsOfFile:path password:password]];}//获取私钥+ (SecKeyRef)getPrivateKeyRefWithContentsOfFile:(NSString*)filePath password:(NSString*)password{NSData*p12Data = [NSDatadataWithContentsOfFile:filePath];if(!p12Data) {returnnil;    }    SecKeyRef privateKeyRef =NULL;NSMutableDictionary* options = [[NSMutableDictionaryalloc] init];    [options setObject: password forKey:(__bridgeid)kSecImportExportPassphrase];CFArrayRefitems =CFArrayCreate(NULL,0,0,NULL);    OSStatus securityError = SecPKCS12Import((__bridgeCFDataRef) p12Data, (__bridgeCFDictionaryRef)options, &items);if(securityError == noErr &&CFArrayGetCount(items) >0) {CFDictionaryRefidentityDict =CFArrayGetValueAtIndex(items,0);        SecIdentityRef identityApp = (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:str options:NSDataBase64DecodingIgnoreUnknownCharacters];if(!privKeyRef) {returnnil;    }    data = [selfdecryptData:data withKeyRef:privKeyRef];NSString*ret = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];returnret;}#pragma mark - 使用公钥字符串加密/* START: Encryption with RSA public key *///使用公钥字符串加密+ (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];}+ (SecKeyRef)addPublicKey:(NSString*)key{NSRangespos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];NSRangeepos = [key rangeOfString:@"-----END PUBLIC KEY-----"];if(spos.location!=NSNotFound&& epos.location!=NSNotFound){NSUIntegers = spos.location+ spos.length;NSUIntegere = epos.location;NSRangerange =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 = [selfstripPublicKeyHeader:data];if(!data){returnnil;    }//a tag to read/write keychain storageNSString*tag =@"RSAUtil_PubKey";NSData*d_tag = [NSDatadataWithBytes:[tag UTF8String] length:[tag length]];// Delete any old lingering key with the same tagNSMutableDictionary*publicKey = [[NSMutableDictionaryalloc] 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:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)    kSecReturnPersistentRef];CFTypeRefpersistKey =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:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];    [publicKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];// Now fetch the SecKeyRef version of the keySecKeyRef keyRef =nil;    status = SecItemCopyMatching((__bridgeCFDictionaryRef)publicKey, (CFTypeRef*)&keyRef);if(status != noErr){returnnil;    }returnkeyRef;}+ (NSData*)stripPublicKeyHeader:(NSData*)d_key{// Skip ASN.1 public key headerif(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_RSAstaticunsignedcharseqiod[] =    {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 bufferreturn([NSDatadataWithBytes:&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 = [[NSMutableDataalloc] 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 = [[NSDataalloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];    data = [selfdecryptData:data privateKey:privKey];NSString*ret = [[NSStringalloc] 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];}+ (SecKeyRef)addPrivateKey:(NSString*)key{NSRangespos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];NSRangeepos = [key rangeOfString:@"-----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 = [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 storageNSString*tag =@"RSAUtil_PrivKey";NSData*d_tag = [NSDatadataWithBytes:[tag UTF8String] length:[tag length]];// Delete any old lingering key with the same tagNSMutableDictionary*privateKey = [[NSMutableDictionaryalloc] 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:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)    kSecReturnPersistentRef];CFTypeRefpersistKey =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:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnRef];    [privateKey setObject:(__bridgeid) kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];// Now fetch the SecKeyRef version of the keySecKeyRef keyRef =nil;    status = SecItemCopyMatching((__bridgeCFDictionaryRef)privateKey, (CFTypeRef*)&keyRef);if(status != noErr){returnnil;    }returnkeyRef;}+ (NSData*)stripPrivateKeyHeader:(NSData*)d_key{// Skip ASN.1 private key headerif(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 22if(0x04!= c_key[idx++])returnnil;//calculate length of the keyunsignedintc_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 bufferreturnnil;        }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 bufferreturn[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 = [[NSMutableDataalloc] 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 = 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;                    }                }            }            [ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];        }    }    free(outbuf);CFRelease(keyRef);returnret;}/* END: Decryption with RSA private key */@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容

  • /**ios常见的几种加密方法: 普通的加密方法是讲密码进行加密后保存到用户偏好设置( [NSUserDefaul...
    彬至睢阳阅读 2,912评论 0 7
  • 嘟哝嘟哝:最近接到一个任务:在客户端动态生成RSA密钥对,然后向服务器发送这个密钥对中的公钥字符串,由服务器进行公...
    TimmyR阅读 8,009评论 19 21
  • 死神的镰刀锁定大地,山崩地裂! 死神的镰刀锁定天空,风卷残云! 死神的镰刀锁定世间万物,圣洁之光笼罩伤痕累累的地球...
    逍遙自在唯我獨尊阅读 141评论 1 0
  • 今天23点熄灯,所以在还在收尾《立项报告》的时候就写日志(:зゝ∠) 目标 单词70(√) 算法导论第三章+第四章...
    Courage_CYY阅读 137评论 0 0
  • 师训主题知识掌握能级及四级课程体系的设置 主讲老师刘强 师训时间5月16日14:30 师训地点锦茂校区1310教室...
    16e2c83b34c5阅读 73评论 0 0