之前的项目中接触过一些加密的方法,也没有太仔细的进行记录和研究。最近在写SDK时,加密模块的占比相当之大;借此时机,对我们常用的加密方式做一个笔记。
为什么要做加密操作?
加密就是为了保证我们的数据安全,即不被他人篡改或截取到有用的信息的操作。iOS一直以安全著称,但是从Xcode的Ghost事件之后,iOS安全不可摧的神话似乎已经被打破。事实证明,无论是Android还是iOS,该加密处理的还是需要加密处理,谁也不能保证自己一定是安全的。下面我们来介绍iOS常用到的加密方式。
iOS常用加密方式
常见的iOS代码加密常用加密方式包括Base64加密、MD5加密、AES加密、RSA加密等。无论选择哪种加密算法,最终都是为了保证代码安全,捍卫自己的产品原创性。
Base64加密
Base64编码的思想是:采用64个基本的ASCII码字符对数据进行重新编码。它将需要编码的数据拆分成字节数组,以3个字节为一组,按顺序排列24位数据,再把这24位数据分成4组,即每组6位;再在每组的的最高位前补两个0凑足一个字节,这样就把一个3字节为一组的数据重新编码成了4个字节;当所要编码的数据的字节数不是3的整倍数,也就是说在分组时最后一组不够3个字节,这时在最后一组填充1到2个0字节,并在最后编码完成后在结尾添加1到2个=号。例如:将对ABC进行Base64编码首先取ABC对应的ASCII码值,A : 65、B : 66、C : 67,再取二进制值A : 01000001、B : 01000010、C : 01000011,然后把这三个字节的二进制码接起来010000010100001001000011,再以6位为单位分成4个数据块并在最高位填充两个0后形成4个字节的编码后的值00010000、00010100、00001001、00000011;再把这4个字节数据转化成10进制数得16、20、19、3;最后根据Base64给出的64个基本字符表,查出对应的ASCII码字符Q、U、J、D,这里的值实际就是数据在字符表中的索引。解码过程就是把4个字节再还原成3个字节再根据不同的数据形式把字节数组重新整理成数据。注:Base64字符表,包括大写A-Z小写a-z数字0-9和+以及/。
Base64加密原则:6bit(原8bit)一个字节,不足的位数用0补齐,两个0用一个=表示。
Base64加密特点:
- 数据加密之后,数据量会变大,变大1/3左右。
- 可进行反向解密。
- 编码后有个非常显著的特点,末尾有个=号。
在iOS中Base64加解密使用方法介绍(本例使用系统API,仅支持iOS7及以后的系统版本)
/****************************Base64.m类实现文件内容****************************/+ (NSString*)base64EncodedStringWithData:(NSData*)data{//判断是否传入需要加密数据参数if((data ==nil) || (data ==NULL)) {returnnil; }elseif(![data isKindOfClass:[NSDataclass]]) {returnnil; }//判断设备系统是否满足条件if([[[UIDevicecurrentDevice] systemVersion] doubleValue] <=6.9) {returnnil; }//使用系统的API进行Base64加密操作NSDataBase64EncodingOptionsoptions; options =NSDataBase64EncodingEndLineWithLineFeed;return[data base64EncodedStringWithOptions:options];}+ (NSData*)base64DecodeDataWithString:(NSString*)string{//判断是否传入需要加密数据参数if((string ==nil) || (string ==NULL)) {returnnil; }elseif(![string isKindOfClass:[NSStringclass]]) {returnnil; }//判断设备系统是否满足条件if([[[UIDevicecurrentDevice] systemVersion] doubleValue] <=6.9) {returnnil; }//使用系统的API进行Base64解密操作NSDataBase64DecodingOptionsoptions; options =NSDataBase64DecodingIgnoreUnknownCharacters;return[[NSDataalloc] initWithBase64EncodedString:string options:options];}/*****************************************************************************///使用Base64文件进行Base64加密和解密/*********************************使用Base64类*********************************///使用Base64执行加密操作NSString*string =@"abcdefghijklmnopqrstuvwxyz";NSData*data = [string dataUsingEncoding:NSUTF8StringEncoding];NSString*encodeString = [Base64 base64EncodedStringWithData:data];NSLog(@"encodeString : %@", encodeString);//使用Base64执行解密操作NSString*decodeString =nil;NSData*decodeData = [Base64 base64DecodeDataWithString:encodeString];decodeString = [[NSStringalloc] initWithData:decodeData encoding:NSUTF8StringEncoding];NSLog(@"decodeString : %@", decodeString);/******************************************************************************/
MD5加密(MD5是一种摘要,而非加密,只是经常与加密配合使用)
MD5的全称是Message-DigestAlgorithm 5,Message-Digest泛指字节串(Message)的Hash变换,就是把一个任意长度的字节串变换成一定长的大整数。请注意我使用了字节串而不是字符串这个词,是因为这种变换只与字节的值有关,与字符集或编码方式无关。MD5将任意长度的字节串变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法,换句话说就是,即使你看到源程序和算法描述,也无法将一个MD5的值变换回原始的字符串,从数学原理上说,是因为原始的字符串有无穷多个,这有点象不存在反函数的数学函数。MD5的典型应用是对一段Message(字节串)产生fingerprint(指纹),以防止被"篡改"。举个例子,你将一段话写在一个叫readme.txt文件中,并对这个readme.txt产生一个MD5的值并记录在案,然后你可以传播这个文件给别人,别人如果修改了文件中的任何内容,你对这个文件重新计算MD5时就会发现。如果再有一个第三方的认证机构,用MD5还可以防止文件作者的"抵赖",这就是所谓的数字签名应用。MD5还广泛用于加密和解密技术上,在很多操作系统中,用户的密码是以MD5值(或类似的其它算法)的方式保存的,用户Login的时候,系统是把用户输入的密码计算成MD5值,然后再去和系统中保存的MD5值进行比较,而系统并"不知道"用户的密码是什么。MD5加密大体都应用在:验证数据或文件一致性、数字签名、安全访问认证等等。大概可比喻为:人的指纹来理解。
注:MD5加密是不可逆的,也就是说,MD5加密后是不能解密的,所谓的解密只是用大数据的”试用”,来测出结果的。
MD5特点:
- 压缩性 : 任意长度的数据,算出的MD5值长度都是固定的。
- 容易计算 : 从原数据计算出MD5值很容易。
- 抗修改性 : 对原数据进行任何改动,哪怕只修改一个字节,所得到的MD5值都有很大区别。
- 弱抗碰撞 : 已知原数据和其MD5值,想找到一个具有相同MD5值的数据(即伪造数据)是非常困难的。
- 强抗碰撞 : 想找到两个不同数据,使他们具有相同的MD5值,是非常困难的。
在iOS中MD5加密和验签使用方法介绍
/****************************MD5.m类实现文件内容****************************///对字符串数据进行MD5的签名+ (NSString*)md5SignWithString:(NSString*)string{constchar*object = [string UTF8String];unsignedcharresult[CC_MD5_DIGEST_LENGTH]; CC_MD5(object,(CC_LONG)strlen(object),result);NSMutableString*hash = [NSMutableStringstring];for(inti =0; i <16; i ++) { [hash appendFormat:@"%02X", result[i]]; }return[hash lowercaseString];}//对二进制数据进行MD5的签名+ (NSData*)md5SignWithData:(NSData*)data{ Byte byte[CC_MD5_DIGEST_LENGTH];//定义一个字节数组来接收结果CC_MD5((constvoid*)([data bytes]), (CC_LONG)[data length], byte);return[NSDatadataWithBytes:byte length:CC_MD5_DIGEST_LENGTH];}/******************************************************************************///使用MD5文件进行MD5加密和验签/*********************************使用MD5类*********************************///使用MD5执行加密操作NSString*string2 =@"abcdefghijklmnopqrstuvwxyz";NSString*encodeString2 = [MD5 md5SignWithString:string2];NSLog(@"encodeString2 : %@", encodeString2);//MD5为不可逆的操作,使用MD5执行验签操作NSString*verifyString2 = [MD5 md5SignWithString:string2];NSLog(@"verifyString2 : %@", verifyString2);if([verifyString2 isEqualToString:encodeString2]) {NSLog(@"md5 verify sign success");}else{NSLog(@"md5 verify sign failed");}/******************************************************************************/
AES加密
高级加密标准Advanced Encryption Standard简称:AES,在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。它是一种对称加密算法,这个标准也替代原先的DES标准,已经被多方分析且广为全世界所使用。AES设计有三个密钥长度:128、192、256位,相对而言,AES的128密钥比DES的56密钥强1021倍。AES算法主要包括三个方面:轮变化、圈数和密钥扩展。总体来说,AES作为新一代的数据加密标准汇聚了强安全性、高性能、高效率、易用和灵活,在软件及硬件上都能快速地加解密且只需要很少的存储资源等优点。
AES加密流程介绍无从下笔,直接上图了。
AES加解密特点:
- AES强安全性、高性能、高效率、易用和灵活。
- 在软件及硬件上都能快速地加解密且只需要很少的存储资源。
在iOS中AES加解密的实现介绍
//需要导入:#import 库才能使用/**
* AES128 + ECB + PKCS7
* @param data 要加密的原始数据
* @param key 加密 key
* @return 加密后数据
*/+ (NSData*)encryptData:(NSData*)data key:(NSData*)key{//判断解密的流数据是否存在if((data ==nil) || (data ==NULL)) {returnnil; }elseif(![data isKindOfClass:[NSDataclass]]) {returnnil; }elseif([data length] <=0) {returnnil; }//判断解密的Key是否存在if((key ==nil) || (key ==NULL)) {returnnil; }elseif(![key isKindOfClass:[NSDataclass]]) {returnnil; }elseif([key length] <=0) {returnnil; }//setup keyNSData*result =nil;unsignedcharcKey[kCCKeySizeAES128]; bzero(cKey,sizeof(cKey)); [key getBytes:cKey length:kCCKeySizeAES128];//setup output buffersize_t bufferSize = [data length] + kCCBlockSizeAES128;void*buffer = malloc(bufferSize);//do encryptsize_t encryptedSize =0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode|kCCOptionPKCS7Padding, cKey, kCCKeySizeAES128,nil, [data bytes], [data length], buffer, bufferSize, &encryptedSize);if(cryptStatus == kCCSuccess) { result = [NSDatadataWithBytesNoCopy:buffer length:encryptedSize]; }else{ free(buffer); }returnresult;}/**
* AES128 + ECB + PKCS7
* @param data 要解密的原始数据
* @param key 解密 key
* @return 解密后数据
*/+ (NSData*)decryptData:(NSData*)data key:(NSData*)key{//判断解密的流数据是否存在if((data ==nil) || (data ==NULL)) {returnnil; }elseif(![data isKindOfClass:[NSDataclass]]) {returnnil; }elseif([data length] <=0) {returnnil; }//判断解密的Key是否存在if((key ==nil) || (key ==NULL)) {returnnil; }elseif(![key isKindOfClass:[NSDataclass]]) {returnnil; }elseif([key length] <=0) {returnnil; }//setup keyNSData*result =nil;unsignedcharcKey[kCCKeySizeAES128]; bzero(cKey,sizeof(cKey)); [key getBytes:cKey length:kCCKeySizeAES128];//setup output buffersize_t bufferSize = [data length] + kCCBlockSizeAES128;void*buffer = malloc(bufferSize);//do decryptsize_t decryptedSize =0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionECBMode|kCCOptionPKCS7Padding, cKey, kCCKeySizeAES128,nil, [data bytes], [data length], buffer, bufferSize, &decryptedSize);if(cryptStatus == kCCSuccess) { result = [NSDatadataWithBytesNoCopy:buffer length:decryptedSize]; }else{ free(buffer); }returnresult;}
在iOS中AES加解密使用方法介绍
//使用AES执行加密操作NSString*aesKey =@"a1b2c3d4e5f6g7h8";NSString*string3 =@"abcdefghijklmnopqrstuvwxyz";NSData*keyData3 = [aesKey dataUsingEncoding:NSUTF8StringEncoding];NSData*sourceData3 = [string3 dataUsingEncoding:NSUTF8StringEncoding];NSData*encodeData3 = [AESEncrypt encryptData:sourceData3 key:keyData3];NSLog(@"encodeData3 : %@", encodeData3);//使用AES执行解密操作NSString*decodeString3 =nil;NSData*decodeData3 = [AESEncrypt decryptData:encodeData3 key:keyData3];decodeString3 = [[NSStringalloc] initWithData:decodeData3 encoding:NSUTF8StringEncoding];NSLog(@"decodeString3 : %@", decodeString3);
RSA加密
RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。RSA的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。通常是先生成一对RSA密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公开,甚至可在网络服务器中注册。为提高保密强度,RSA密钥至少为500位长,一般推荐使用1024位,这就使加密的计算量很大。为减少计算量,在传送信息时,常采用传统加密方法与公开密钥加密方法相结合的方式,即信息采用改进的DES或IDEA对话密钥加密,然后使用RSA密钥加密对话密钥和信息摘要,对方收到信息后,用不同的密钥解密并可核对信息摘要。RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作,RSA是被研究得最广泛的公钥算法。RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。RSA加密大体都应用在:本地数据加密、网络传输数据加密、方法体和方法名高级混淆以及程序结构混排加密。例如:对客户端传输数据提供加密方案,有效防止通过网络接口的拦截获取。
RSA的算法涉及三个参数,n、e1、e2。其中,n是两个大质数p、q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。e1和e2是一对相关的值,e1可以任意取,但要求e1与(p-1)(q-1)互质;再选择e2,要求(e2e1)mod((p-1)*(q-1))=1。(n,e1),(n,e2)就是密钥对。其中(n,e1)为公钥,(n,e2)为私钥;RSA加解密的算法完全相同,公钥加密体制中,一般用公钥加密,私钥解密。假设A为明文,B为密文,则:A=B^e2 mod n;B=A^e1 mod n;e1和e2可以互换使用,即私钥加密,公钥解密,公式:A=B^e1 mod n;B=A^e2 mod n;
RSA加解密特点:
- RSA密钥管理的方便,计算量很大速度相对比较慢。
- RSA安全性很高,能够抵抗到目前为止已知的绝大多数密码攻击。
在线生成RSA密钥对的网址:在线生成非对称加密公钥私钥对等,RSA密钥格式请使用PKCS#8格式。PKCS#1与PKCS#8的区别还待后续查阅资料,再进行补充记录。
在iOS中RSA加解密的实现介绍(支持密钥文件<.pem>和字符串密钥)
/****************************RSAEncrypt.m类实现文件内容****************************/#pragma mark - Class Utils Method+ (BOOL)isEmptyKeyRef:(id)object{if(object ==nil) {returnYES; }elseif(object ==NULL) {returnYES; }elseif(object == [NSNullnull]) {returnYES; }returnNO;}#pragma mark - Private Method+ (SecKeyRef)getPrivateKeyRefWithFilePath:(NSString*)filePath keyPassword:(NSString*)keyPassword{//读取私钥证书文件的内容NSData*certificateData = [NSDatadataWithContentsOfFile:filePath];if((certificateData ==nil) || (certificateData ==NULL)) {returnnil; }elseif(![certificateData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([certificateData length] <=0) {returnnil; }//拼接密码参数到字典中NSString*passwordKey = (__bridgeid)kSecImportExportPassphrase;NSString*passwordValue = [NSStringstringWithFormat:@"%@",keyPassword];if((keyPassword ==nil) || (keyPassword ==NULL)) { passwordValue =@""; }elseif(![keyPassword isKindOfClass:[NSStringclass]]) { passwordValue =@""; }elseif([keyPassword length] <=0) { passwordValue =@""; }NSMutableDictionary*optionInfo = [[NSMutableDictionaryalloc] init]; [optionInfo setObject:passwordValue forKey:passwordKey];//获取私钥对象SecKeyRef privateKeyRef =NULL;CFArrayRefitems =CFArrayCreate(NULL,0,0,NULL);CFDataRefpkcs12Data = (__bridgeCFDataRef)certificateData;CFDictionaryRefoptions = (__bridgeCFDictionaryRef)optionInfo; OSStatus securityStatus = SecPKCS12Import(pkcs12Data, options, &items);if(securityStatus == noErr &&CFArrayGetCount(items) >0) { SecIdentityRef identity;constvoid*secpkey = kSecImportItemIdentity;CFDictionaryRefidentityDict =CFArrayGetValueAtIndex(items,0); identity = (SecIdentityRef)CFDictionaryGetValue(identityDict,secpkey); securityStatus = SecIdentityCopyPrivateKey(identity, &privateKeyRef);if(securityStatus != noErr) { privateKeyRef =NULL; } }CFRelease(items);returnprivateKeyRef;}+ (SecKeyRef)privateKeyRefWithPrivateKey:(NSString*)privateKey{//判断参数是否正确if((privateKey ==nil) || (privateKey ==NULL)) {returnnil; }elseif(![privateKey isKindOfClass:[NSStringclass]]) {returnnil; }elseif([privateKey length] <=0) {returnnil; }//解析私钥对象内容NSString*pKey = [NSStringstringWithFormat:@"%@",privateKey];NSRangesposition = [pKey rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];NSRangeeposition = [pKey rangeOfString:@"-----END RSA PRIVATE KEY-----"];if(sposition.location !=NSNotFound&& eposition.location !=NSNotFound) {NSUIntegerendposition = eposition.location;NSUIntegerstartposition = sposition.location + sposition.length;NSRangerange =NSMakeRange(startposition, endposition-startposition); pKey = [pKey substringWithRange:range]; } pKey = [pKey stringByReplacingOccurrencesOfString:@"\r"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@"\n"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@"\t"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@" "withString:@""];//This will be base64 encoded, decode it.NSData*keyData = [Base64 base64DecodeDataWithString:pKey]; keyData = [selfstripPrivateKeyHeader:keyData];if((keyData ==nil) || (keyData ==NULL)) {returnnil; }elseif(![keyData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([keyData length] <=0) {returnnil; }//a tag to read/write keychain storageNSString*tag =@"RSAUtil_PrivKey";constvoid*bytes = [tag UTF8String];NSData*tagData = [NSDatadataWithBytes:bytes length:[tag length]];//Delete any old lingering key with the same tagNSMutableDictionary*attributes = [[NSMutableDictionaryalloc] init]; [attributes setObject:(__bridgeid)kSecClassKey forKey:(__bridgeid)kSecClass]; [attributes setObject:(__bridgeid)kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType]; [attributes setObject:tagData forKey:(__bridgeid)kSecAttrApplicationTag]; SecItemDelete((__bridgeCFDictionaryRef)attributes);//Add persistent version of the key to system keychain[attributes setObject:keyData forKey:(__bridgeid)kSecValueData]; [attributes setObject:(__bridgeid)kSecAttrKeyClassPrivate forKey:(__bridgeid)kSecAttrKeyClass]; [attributes setObject:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnPersistentRef]; OSStatus status = noErr;CFTypeRefpersistKey =nil; status = SecItemAdd((__bridgeCFDictionaryRef)attributes, &persistKey);if(persistKey !=nil) {CFRelease(persistKey);}if((status != noErr) && (status != errSecDuplicateItem)) {returnnil; } [attributes removeObjectForKey:(__bridgeid)kSecValueData]; [attributes removeObjectForKey:(__bridgeid)kSecReturnPersistentRef]; [attributes setObject:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnRef]; [attributes setObject:(__bridgeid)kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];//Now fetch the SecKeyRef version of the keySecKeyRef keyRef =nil;CFDictionaryRefquery = (__bridgeCFDictionaryRef)attributes; status = SecItemCopyMatching(query, (CFTypeRef*)&keyRef);if(status != noErr) {returnnil; }returnkeyRef;}+ (NSData*)stripPrivateKeyHeader:(NSData*)d_key{//Skip ASN.1 private key headerif(d_key ==nil)returnnil;unsignedlonglen = [d_key length];if(!len)returnnil;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++];if(!(c_len &0x80)) { 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)];}+ (SecKeyRef)getPublicKeyRefWithFilePath:(NSString*)filePath{//读取公钥证书文件的内容NSData*certificateData = [NSDatadataWithContentsOfFile:filePath];if((certificateData ==nil) || (certificateData ==NULL)) {returnnil; }elseif(![certificateData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([certificateData length] <=0) {returnnil; }//将公钥证书制作成证书对象CFDataRefdata = (__bridgeCFDataRef)certificateData; SecCertificateRef certificateRef = SecCertificateCreateWithData(NULL, data);//获取公钥对象SecTrustRef trust =NULL; SecKeyRef publicKey =NULL; SecPolicyRef policies = SecPolicyCreateBasicX509();if(![[selfclass] isEmptyKeyRef:(__bridgeid)(certificateRef)] && ![[selfclass] isEmptyKeyRef:(__bridgeid)(policies)]) { OSStatus status; status = SecTrustCreateWithCertificates((CFTypeRef)certificateRef, policies, &trust);if(status == noErr) { SecTrustResultType result;if(SecTrustEvaluate(trust, &result) == noErr) { publicKey = SecTrustCopyPublicKey(trust); } } }if(certificateRef !=NULL)CFRelease(certificateRef);if(policies !=NULL)CFRelease(policies);if(trust !=NULL)CFRelease(trust);returnpublicKey;}+ (SecKeyRef)publicKeyRefWithPublicKey:(NSString*)publicKey{//判断参数是否正确if((publicKey ==nil) || (publicKey ==NULL)) {returnnil; }elseif(![publicKey isKindOfClass:[NSStringclass]]) {returnnil; }elseif([publicKey length] <=0) {returnnil; }//解析公钥对象内容NSString*pKey = [NSStringstringWithFormat:@"%@",publicKey];NSRangesposition = [pKey rangeOfString:@"-----BEGIN PUBLIC KEY-----"];NSRangeeposition = [pKey rangeOfString:@"-----END PUBLIC KEY-----"];if(sposition.location !=NSNotFound&& eposition.location !=NSNotFound) {NSUIntegerstartposition = eposition.location;NSUIntegerendposition = sposition.location + sposition.length;NSRangerange =NSMakeRange(endposition, startposition-endposition); pKey = [pKey substringWithRange:range]; } pKey = [pKey stringByReplacingOccurrencesOfString:@"\r"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@"\n"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@"\t"withString:@""]; pKey = [pKey stringByReplacingOccurrencesOfString:@" "withString:@""];//This will be base64 encoded, decode it.NSData*keyData = [[selfclass] base64DecodeDataWithString:pKey]; keyData = [selfstripPublicKeyHeader:keyData];if((keyData ==nil) || (keyData ==NULL)) {returnnil; }elseif(![keyData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([keyData length] <=0) {returnnil; }//a tag to read/write keychain storageNSString*tag =@"RSAUtil_PubKey";constvoid*bytes = [tag UTF8String];NSData*tagData = [NSDatadataWithBytes:bytes length:[tag length]];//Delete any old lingering key with the same tagNSMutableDictionary*attributes = [[NSMutableDictionaryalloc] init]; [attributes setObject:(__bridgeid)kSecClassKey forKey:(__bridgeid)kSecClass]; [attributes setObject:(__bridgeid)kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType]; [attributes setObject:tagData forKey:(__bridgeid)kSecAttrApplicationTag]; SecItemDelete((__bridgeCFDictionaryRef)attributes);//Add persistent version of the key to system keychain[attributes setObject:keyData forKey:(__bridgeid)kSecValueData]; [attributes setObject:(__bridgeid)kSecAttrKeyClassPublic forKey:(__bridgeid)kSecAttrKeyClass]; [attributes setObject:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnPersistentRef]; OSStatus status = noErr;CFTypeRefpersistKey =nil; status = SecItemAdd((__bridgeCFDictionaryRef)attributes, &persistKey);if(persistKey !=nil)CFRelease(persistKey);if((status != noErr) && (status != errSecDuplicateItem)) {returnnil; } [attributes removeObjectForKey:(__bridgeid)kSecValueData]; [attributes removeObjectForKey:(__bridgeid)kSecReturnPersistentRef]; [attributes setObject:[NSNumbernumberWithBool:YES] forKey:(__bridgeid)kSecReturnRef]; [attributes setObject:(__bridgeid)kSecAttrKeyTypeRSA forKey:(__bridgeid)kSecAttrKeyType];//Now fetch the SecKeyRef version of the keySecKeyRef publicKeyRef =nil;CFDictionaryRefquery = (__bridgeCFDictionaryRef)attributes; status = SecItemCopyMatching(query, (CFTypeRef*)&publicKeyRef);if(status != noErr) {returnnil; }returnpublicKeyRef;}+ (NSData*)stripPublicKeyHeader:(NSData*)d_key{//Skip ASN.1 public key headerif(d_key ==nil) {returnnil;}unsignedlonglen = [d_key length];if(!len)return(nil);unsignedchar*c_key = (unsignedchar*)[d_key bytes];unsignedintidx =0;if(c_key[idx++] !=0x30) {returnnil;}if(c_key[idx] >0x80) { idx += c_key[idx] -0x80+1; }else{ idx++; }//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)) {returnnil;} idx +=15;if(c_key[idx++] !=0x03) {returnnil;}if(c_key[idx] >0x80) { idx += c_key[idx] -0x80+1; }else{ idx ++; }if(c_key[idx++] !='\0') {returnnil;}//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 < srclen; idx += src_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", (int)status); ret =nil;break; }else{ [ret appendBytes:outbuf length:outlen]; } } free(outbuf);CFRelease(keyRef);returnret;}+ (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 < srclen; idx += src_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", (int)status); ret =nil;break; }else{intidxFirstZero =-1;intidxNextZero = (int)outlen;for(inti =0; i < outlen; i ++) {if(outbuf[i] ==0) {if(idxFirstZero <0) { idxFirstZero = i; }else{ idxNextZero = i;break; } } }NSUIntegerlength = idxNextZero-idxFirstZero-1; [ret appendBytes:&outbuf[idxFirstZero+1] length:length]; } } free(outbuf);CFRelease(keyRef);returnret;}#pragma mark - RSA Key File Encrypt/Decrypt Public Method+ (NSString*)encryptString:(NSString*)originString publicKeyPath:(NSString*)publicKeyPath{//判断originString参数是否正确if((originString ==nil) || (originString ==NULL)) {returnnil; }elseif(![originString isKindOfClass:[NSStringclass]]) {returnnil; }elseif([originString length] <=0) {returnnil; }//判断publicKeyPath参数是否正确if((publicKeyPath ==nil) || (publicKeyPath ==NULL)) {returnnil; }elseif(![publicKeyPath isKindOfClass:[NSStringclass]]) {returnnil; }elseif([publicKeyPath length] <=0) {returnnil; }//获取公钥对象和需要加密的字符串内容编码数据流SecKeyRef publicKeyRef = [selfgetPublicKeyRefWithFilePath:publicKeyPath];NSData*originData = [originString dataUsingEncoding:NSUTF8StringEncoding];if([[selfclass] isEmptyKeyRef:(__bridgeid)(publicKeyRef)]) {returnnil; }if((originData ==nil) || (originData ==NULL)) {returnnil; }elseif(![originData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([originData length] <=0) {returnnil; }//加密源字符串内容编码数据流的数据NSData*resultData =nil; resultData = [selfencryptData:originData withKeyRef:publicKeyRef];return[[selfclass] base64EncodedStringWithData:resultData];}+ (NSString*)decryptString:(NSString*)encryptString privateKeyPath:(NSString*)privateKeyPath privateKeyPwd:(NSString*)privateKeyPwd{//判断encryptString参数是否正确if((encryptString ==nil) || (encryptString ==NULL)) {returnnil; }elseif(![encryptString isKindOfClass:[NSStringclass]]) {returnnil; }elseif([encryptString length] <=0) {returnnil; }//判断publicKeyPath参数是否正确if((privateKeyPath ==nil) || (privateKeyPath ==NULL)) {returnnil; }elseif(![privateKeyPath isKindOfClass:[NSStringclass]]) {returnnil; }elseif([privateKeyPath length] <=0) {returnnil; }//判断密码是否存在NSString*keyPassword = [NSStringstringWithFormat:@"%@",privateKeyPwd];if((privateKeyPwd ==nil) || (privateKeyPwd ==NULL)) { keyPassword =@""; }elseif(![privateKeyPwd isKindOfClass:[NSStringclass]]) { keyPassword =@""; }elseif([privateKeyPwd length] <=0) { keyPassword =@""; }//获取私钥对象和需要加密的字符串内容编码数据流NSData*encryptData =nil, *decryptData =nil; SecKeyRef privateKeyRef = [selfgetPrivateKeyRefWithFilePath:privateKeyPath keyPassword:privateKeyPwd]; encryptData = [[selfclass] base64DecodeDataWithString:encryptString];if([[selfclass] isEmptyKeyRef:(__bridgeid)(privateKeyRef)]) {returnnil; }if((encryptData ==nil) || (encryptData ==NULL)) {returnnil; }elseif(![encryptData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([encryptData length] <=0) {returnnil; }NSStringEncodingencoding =NSUTF8StringEncoding; decryptData = [selfdecryptData:encryptData withKeyRef:privateKeyRef];return[[NSStringalloc] initWithData:decryptData encoding:encoding];}#pragma mark - RSA Key String Encrypt/Decrypt Public Method+ (NSData*)encryptData:(NSData*)originData publicKey:(NSString*)publicKey{//判断originData参数是否正确if((originData ==nil) || (originData ==NULL)) {returnnil; }elseif(![originData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([originData length] <=0) {returnnil; }//判断publicKeyPath参数是否正确if((publicKey ==nil) || (publicKey ==NULL)) {returnnil; }elseif(![publicKey isKindOfClass:[NSStringclass]]) {returnnil; }elseif([publicKey length] <=0) {returnnil; }//获取需要加密的字符串内容编码数据流SecKeyRef publicKeyRef = [selfpublicKeyRefWithPublicKey:publicKey];if([[selfclass] isEmptyKeyRef:(__bridgeid)(publicKeyRef)]){returnnil; }return[selfencryptData:originData withKeyRef:publicKeyRef];}+ (NSString*)encryptString:(NSString*)originString publicKey:(NSString*)publicKey{//判断publicKey参数是否正确if((publicKey ==nil) || (publicKey ==NULL)) {returnnil; }elseif(![publicKey isKindOfClass:[NSStringclass]]) {returnnil; }elseif([publicKey length] <=0) {returnnil; }//判断originString参数是否正确if((originString ==nil) || (originString ==NULL)) {returnnil; }elseif(![originString isKindOfClass:[NSStringclass]]) {returnnil; }elseif([originString length] <=0) {returnnil; }//获取需要加密的字符串内容编码数据流NSData*originData =nil, *encryptData =nil; SecKeyRef publicKeyRef = [selfpublicKeyRefWithPublicKey:publicKey]; originData = [originString dataUsingEncoding:NSUTF8StringEncoding];if([[selfclass] isEmptyKeyRef:(__bridgeid)(publicKeyRef)]){returnnil; }if((originData ==nil) || (originData ==NULL)) {returnnil; }elseif(![originData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([originData length] <=0) {returnnil; } encryptData = [selfencryptData:originData withKeyRef:publicKeyRef];return[[selfclass] base64EncodedStringWithData:encryptData];}+ (NSString*)decryptString:(NSString*)encryptString privateKey:(NSString*)privateKey{//判断publicKey参数是否正确if((privateKey ==nil) || (privateKey ==NULL)) {returnnil; }elseif(![privateKey isKindOfClass:[NSStringclass]]) {returnnil; }elseif([privateKey length] <=0) {returnnil; }//判断originString参数是否正确if((encryptString ==nil) || (encryptString ==NULL)) {returnnil; }elseif(![encryptString isKindOfClass:[NSStringclass]]) {returnnil; }elseif([encryptString length] <=0) {returnnil; }//获取私钥对象和需要加密的字符串内容编码数据流SecKeyRef privateKeyRef;NSData*encryptData =nil, *decryptData =nil; privateKeyRef = [[selfclass] privateKeyRefWithPrivateKey:privateKey]; encryptData = [[selfclass] base64DecodeDataWithString:encryptString];if([[selfclass] isEmptyKeyRef:(__bridgeid)(privateKeyRef)]) {returnnil; }if((encryptData ==nil) || (encryptData ==NULL)) {returnnil; }elseif(![encryptData isKindOfClass:[NSDataclass]]) {returnnil; }elseif([encryptData length] <=0) {returnnil; }NSStringEncodingencoding =NSUTF8StringEncoding; decryptData = [selfdecryptData:encryptData withKeyRef:privateKeyRef];return[[NSStringalloc] initWithData:decryptData encoding:encoding];}/******************************************************************************/
在iOS中RSA加解密使用方法介绍(RSA密钥格式请使用PKCS#8格式)
//使用RSA执行加密操作NSString*string4 =@"abcdefghijklmnopqrstuvwxyz";NSString*encodeString4 = [RSAEncrypt encryptString:string4 publicKey:mPublicKey];NSLog(@"encodeString4 : %@", encodeString4);//使用RSA执行解密操作NSString*decodeString4 = [RSAEncrypt decryptString:encodeString4 privateKey:mPrivateKey];NSLog(@"decodeString4 : %@", decodeString4);
作者:晚街听風丶
链接:https://www.jianshu.com/p/d9cd97c77549
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。