#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
11
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)座享,“玉大人婉商,你說我怎么就攤上這事≡眩” “怎么了丈秩?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)淳衙。 經(jīng)常有香客問我蘑秽,道長(zhǎng),這世上最難降的妖魔是什么箫攀? 我笑而不...
- 正文 為了忘掉前任肠牲,我火速辦了婚禮,結(jié)果婚禮上靴跛,老公的妹妹穿的比我還像新娘缀雳。我一直安慰自己,他們只是感情好梢睛,可當(dāng)我...
- 文/花漫 我一把揭開白布肥印。 她就那樣靜靜地躺著,像睡著了一般绝葡。 火紅的嫁衣襯著肌膚如雪竖独。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼坦辟,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了章办?” 一聲冷哼從身側(cè)響起锉走,我...
- 序言:老撾萬(wàn)榮一對(duì)情侶失蹤滨彻,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后挪蹭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體亭饵,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年梁厉,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了辜羊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
- 正文 年R本政府宣布,位于F島的核電站上忍,受9級(jí)特大地震影響舍悯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜睡雇,卻給世界環(huán)境...
- 文/蒙蒙 一萌衬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧它抱,春花似錦秕豫、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至侮穿,卻和暖如春歌径,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背亲茅。 一陣腳步聲響...
- 正文 我出身青樓茵肃,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親袭祟。 傳聞我的和親對(duì)象是個(gè)殘疾皇子验残,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- /**ios常見的幾種加密方法: 普通的加密方法是講密碼進(jìn)行加密后保存到用戶偏好設(shè)置( [NSUserDefaul...
- 嘟噥嘟噥:最近接到一個(gè)任務(wù):在客戶端動(dòng)態(tài)生成RSA密鑰對(duì),然后向服務(wù)器發(fā)送這個(gè)密鑰對(duì)中的公鑰字符串巾乳,由服務(wù)器進(jìn)行公...
- 死神的鐮刀鎖定大地您没,山崩地裂鸟召! 死神的鐮刀鎖定天空,風(fēng)卷殘?jiān)疲?死神的鐮刀鎖定世間萬(wàn)物氨鹏,圣潔之光籠罩傷痕累累的地球...
- 今天23點(diǎn)熄燈欧募,所以在還在收尾《立項(xiàng)報(bào)告》的時(shí)候就寫日志(:зゝ∠) 目標(biāo) 單詞70(√) 算法導(dǎo)論第三章+第四章...
- 師訓(xùn)主題知識(shí)掌握能級(jí)及四級(jí)課程體系的設(shè)置 主講老師劉強(qiáng) 師訓(xùn)時(shí)間5月16日14:30 師訓(xùn)地點(diǎn)錦茂校區(qū)1310教室...