#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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...