之前的项目中接触过一些加密的方法,也没有太仔细的进行记录和研究。最近在写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)) {
return nil;
} else if (![data isKindOfClass:[NSData class]]) {
return nil;
}
//判断设备系统是否满足条件
if ([[[UIDevice currentDevice] systemVersion] doubleValue] <= 6.9) {
return nil;
}
//使用系统的API进行Base64加密操作
NSDataBase64EncodingOptions options;
options = NSDataBase64EncodingEndLineWithLineFeed;
return [data base64EncodedStringWithOptions:options];
}
+ (NSData *)base64DecodeDataWithString:(NSString *)string
{
//判断是否传入需要加密数据参数
if ((string == nil) || (string == NULL)) {
return nil;
} else if (![string isKindOfClass:[NSString class]]) {
return nil;
}
//判断设备系统是否满足条件
if ([[[UIDevice currentDevice] systemVersion] doubleValue] <= 6.9) {
return nil;
}
//使用系统的API进行Base64解密操作
NSDataBase64DecodingOptions options;
options = NSDataBase64DecodingIgnoreUnknownCharacters;
return [[NSData alloc] 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 = [[NSString alloc] 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
{
const char *object = [string UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(object,(CC_LONG)strlen(object),result);
NSMutableString *hash = [NSMutableString string];
for (int i = 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((const void*)([data bytes]), (CC_LONG)[data length], byte);
return [NSData dataWithBytes: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 <CommonCrypto/CommonCrypto.h>库才能使用
/**
* AES128 + ECB + PKCS7
* @param data 要加密的原始数据
* @param key 加密 key
* @return 加密后数据
*/
+ (NSData *)encryptData:(NSData *)data key:(NSData *)key
{
//判断解密的流数据是否存在
if ((data == nil) || (data == NULL)) {
return nil;
} else if (![data isKindOfClass:[NSData class]]) {
return nil;
} else if ([data length] <= 0) {
return nil;
}
//判断解密的Key是否存在
if ((key == nil) || (key == NULL)) {
return nil;
} else if (![key isKindOfClass:[NSData class]]) {
return nil;
} else if ([key length] <= 0) {
return nil;
}
//setup key
NSData *result = nil;
unsigned char cKey[kCCKeySizeAES128];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:kCCKeySizeAES128];
//setup output buffer
size_t bufferSize = [data length] + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
//do encrypt
size_t encryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionECBMode|kCCOptionPKCS7Padding,
cKey,
kCCKeySizeAES128,
nil,
[data bytes],
[data length],
buffer,
bufferSize,
&encryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
} else {
free(buffer);
}
return result;
}
/**
* AES128 + ECB + PKCS7
* @param data 要解密的原始数据
* @param key 解密 key
* @return 解密后数据
*/
+ (NSData *)decryptData:(NSData *)data key:(NSData *)key
{
//判断解密的流数据是否存在
if ((data == nil) || (data == NULL)) {
return nil;
} else if (![data isKindOfClass:[NSData class]]) {
return nil;
} else if ([data length] <= 0) {
return nil;
}
//判断解密的Key是否存在
if ((key == nil) || (key == NULL)) {
return nil;
} else if (![key isKindOfClass:[NSData class]]) {
return nil;
} else if ([key length] <= 0) {
return nil;
}
//setup key
NSData *result = nil;
unsigned char cKey[kCCKeySizeAES128];
bzero(cKey, sizeof(cKey));
[key getBytes:cKey length:kCCKeySizeAES128];
//setup output buffer
size_t bufferSize = [data length] + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
//do decrypt
size_t decryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionECBMode|kCCOptionPKCS7Padding,
cKey,
kCCKeySizeAES128,
nil,
[data bytes],
[data length],
buffer,
bufferSize,
&decryptedSize);
if (cryptStatus == kCCSuccess) {
result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
} else {
free(buffer);
}
return result;
}
在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 = [[NSString alloc] 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) {
return YES;
} else if (object == NULL) {
return YES;
} else if (object == [NSNull null]) {
return YES;
}
return NO;
}
#pragma mark - Private Method
+ (SecKeyRef)getPrivateKeyRefWithFilePath:(NSString *)filePath keyPassword:(NSString *)keyPassword
{
//读取私钥证书文件的内容
NSData *certificateData = [NSData dataWithContentsOfFile:filePath];
if ((certificateData == nil) || (certificateData == NULL)) {
return nil;
} else if (![certificateData isKindOfClass:[NSData class]]) {
return nil;
} else if ([certificateData length] <= 0) {
return nil;
}
//拼接密码参数到字典中
NSString *passwordKey = (__bridge id)kSecImportExportPassphrase;
NSString *passwordValue = [NSString stringWithFormat:@"%@",keyPassword];
if ((keyPassword == nil) || (keyPassword == NULL)) {
passwordValue = @"";
} else if (![keyPassword isKindOfClass:[NSString class]]) {
passwordValue = @"";
} else if ([keyPassword length] <= 0) {
passwordValue = @"";
}
NSMutableDictionary *optionInfo = [[NSMutableDictionary alloc] init];
[optionInfo setObject:passwordValue forKey:passwordKey];
//获取私钥对象
SecKeyRef privateKeyRef = NULL;
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
CFDataRef pkcs12Data = (__bridge CFDataRef)certificateData;
CFDictionaryRef options = (__bridge CFDictionaryRef)optionInfo;
OSStatus securityStatus = SecPKCS12Import(pkcs12Data, options, &items);
if (securityStatus == noErr && CFArrayGetCount(items) > 0)
{
SecIdentityRef identity;
const void *secpkey = kSecImportItemIdentity;
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
identity = (SecIdentityRef)CFDictionaryGetValue(identityDict,secpkey);
securityStatus = SecIdentityCopyPrivateKey(identity, &privateKeyRef);
if (securityStatus != noErr)
{
privateKeyRef = NULL;
}
}
CFRelease(items);
return privateKeyRef;
}
+ (SecKeyRef)privateKeyRefWithPrivateKey:(NSString *)privateKey
{
//判断参数是否正确
if ((privateKey == nil) || (privateKey == NULL)) {
return nil;
} else if (![privateKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([privateKey length] <= 0) {
return nil;
}
//解析私钥对象内容
NSString *pKey = [NSString stringWithFormat:@"%@",privateKey];
NSRange sposition = [pKey rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
NSRange eposition = [pKey rangeOfString:@"-----END RSA PRIVATE KEY-----"];
if (sposition.location != NSNotFound && eposition.location != NSNotFound)
{
NSUInteger endposition = eposition.location;
NSUInteger startposition = sposition.location + sposition.length;
NSRange range = 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 = [self stripPrivateKeyHeader:keyData];
if ((keyData == nil) || (keyData == NULL)) {
return nil;
} else if (![keyData isKindOfClass:[NSData class]]) {
return nil;
} else if ([keyData length] <= 0) {
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PrivKey";
const void *bytes = [tag UTF8String];
NSData *tagData = [NSData dataWithBytes:bytes length:[tag length]];
//Delete any old lingering key with the same tag
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:(__bridge id)kSecClassKey
forKey:(__bridge id)kSecClass];
[attributes setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
[attributes setObject:tagData
forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)attributes);
//Add persistent version of the key to system keychain
[attributes setObject:keyData forKey:(__bridge id)kSecValueData];
[attributes setObject:(__bridge id)kSecAttrKeyClassPrivate
forKey:(__bridge id)kSecAttrKeyClass];
[attributes setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecReturnPersistentRef];
OSStatus status = noErr;
CFTypeRef persistKey = nil;
status = SecItemAdd((__bridge CFDictionaryRef)attributes, &persistKey);
if (persistKey != nil) {CFRelease(persistKey);}
if ((status != noErr) && (status != errSecDuplicateItem))
{
return nil;
}
[attributes removeObjectForKey:(__bridge id)kSecValueData];
[attributes removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[attributes setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecReturnRef];
[attributes setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
//Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
CFDictionaryRef query = (__bridge CFDictionaryRef)attributes;
status = SecItemCopyMatching(query, (CFTypeRef *)&keyRef);
if (status != noErr)
{
return nil;
}
return keyRef;
}
+ (NSData *)stripPrivateKeyHeader:(NSData *)d_key
{
//Skip ASN.1 private key header
if (d_key == nil) return nil;
unsigned long len = [d_key length];
if (!len) return nil;
unsigned char *c_key = (unsigned char *)[d_key bytes];
unsigned int idx = 22; //magic byte at offset 22
if (0x04 != c_key[idx++]) return nil;
//calculate length of the key
unsigned int c_len = c_key[idx++];
if (!(c_len & 0x80))
{
c_len = c_len & 0x7f;
}
else
{
int byteCount = c_len & 0x7f;
if (byteCount + idx > len) {
//rsa length field longer than buffer
return nil;
}
unsigned int accum = 0;
unsigned char *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)];
}
+ (SecKeyRef)getPublicKeyRefWithFilePath:(NSString *)filePath
{
//读取公钥证书文件的内容
NSData *certificateData = [NSData dataWithContentsOfFile:filePath];
if ((certificateData == nil) || (certificateData == NULL)) {
return nil;
} else if (![certificateData isKindOfClass:[NSData class]]) {
return nil;
} else if ([certificateData length] <= 0) {
return nil;
}
//将公钥证书制作成证书对象
CFDataRef data = (__bridge CFDataRef)certificateData;
SecCertificateRef certificateRef = SecCertificateCreateWithData(NULL, data);
//获取公钥对象
SecTrustRef trust = NULL;
SecKeyRef publicKey = NULL;
SecPolicyRef policies = SecPolicyCreateBasicX509();
if (![[self class] isEmptyKeyRef:(__bridge id)(certificateRef)]
&& ![[self class] isEmptyKeyRef:(__bridge id)(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);
return publicKey;
}
+ (SecKeyRef)publicKeyRefWithPublicKey:(NSString *)publicKey
{
//判断参数是否正确
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//解析公钥对象内容
NSString *pKey = [NSString stringWithFormat:@"%@",publicKey];
NSRange sposition = [pKey rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
NSRange eposition = [pKey rangeOfString:@"-----END PUBLIC KEY-----"];
if (sposition.location != NSNotFound && eposition.location != NSNotFound)
{
NSUInteger startposition = eposition.location;
NSUInteger endposition = sposition.location + sposition.length;
NSRange range = 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 = [[self class] base64DecodeDataWithString:pKey];
keyData = [self stripPublicKeyHeader:keyData];
if ((keyData == nil) || (keyData == NULL)) {
return nil;
} else if (![keyData isKindOfClass:[NSData class]]) {
return nil;
} else if ([keyData length] <= 0) {
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PubKey";
const void *bytes = [tag UTF8String];
NSData *tagData = [NSData dataWithBytes:bytes length:[tag length]];
//Delete any old lingering key with the same tag
NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init];
[attributes setObject:(__bridge id)kSecClassKey
forKey:(__bridge id)kSecClass];
[attributes setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
[attributes setObject:tagData
forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)attributes);
//Add persistent version of the key to system keychain
[attributes setObject:keyData
forKey:(__bridge id)kSecValueData];
[attributes setObject:(__bridge id)kSecAttrKeyClassPublic
forKey:(__bridge id)kSecAttrKeyClass];
[attributes setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecReturnPersistentRef];
OSStatus status = noErr;
CFTypeRef persistKey = nil;
status = SecItemAdd((__bridge CFDictionaryRef)attributes, &persistKey);
if (persistKey != nil) CFRelease(persistKey);
if ((status != noErr) && (status != errSecDuplicateItem))
{
return nil;
}
[attributes removeObjectForKey:(__bridge id)kSecValueData];
[attributes removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[attributes setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecReturnRef];
[attributes setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
//Now fetch the SecKeyRef version of the key
SecKeyRef publicKeyRef = nil;
CFDictionaryRef query = (__bridge CFDictionaryRef)attributes;
status = SecItemCopyMatching(query, (CFTypeRef *)&publicKeyRef);
if (status != noErr)
{
return nil;
}
return publicKeyRef;
}
+ (NSData *)stripPublicKeyHeader:(NSData *)d_key
{
//Skip ASN.1 public key header
if (d_key == nil) {return nil;}
unsigned long len = [d_key length];
if (!len) return(nil);
unsigned char *c_key = (unsigned char *)[d_key bytes];
unsigned int idx = 0;
if (c_key[idx++] != 0x30) {return nil;}
if (c_key[idx] > 0x80)
{
idx += c_key[idx] - 0x80 + 1;
}
else
{
idx++;
}
//PKCS #1 rsaEncryption szOID_RSA_RSA
static unsigned char seqiod[] = {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;
}
else
{
idx ++;
}
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
{
const uint8_t *srcbuf = (const uint8_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 (int idx = 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);
return ret;
}
+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef)keyRef
{
const uint8_t *srcbuf = (const uint8_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 (int idx = 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
{
int idxFirstZero = -1;
int idxNextZero = (int)outlen;
for (int i = 0; i < outlen; i ++)
{
if (outbuf[i] == 0)
{
if (idxFirstZero < 0)
{
idxFirstZero = i;
}
else
{
idxNextZero = i;
break;
}
}
}
NSUInteger length = idxNextZero-idxFirstZero-1;
[ret appendBytes:&outbuf[idxFirstZero+1] length:length];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
#pragma mark - RSA Key File Encrypt/Decrypt Public Method
+ (NSString *)encryptString:(NSString *)originString publicKeyPath:(NSString *)publicKeyPath
{
//判断originString参数是否正确
if ((originString == nil) || (originString == NULL)) {
return nil;
} else if (![originString isKindOfClass:[NSString class]]) {
return nil;
} else if ([originString length] <= 0) {
return nil;
}
//判断publicKeyPath参数是否正确
if ((publicKeyPath == nil) || (publicKeyPath == NULL)) {
return nil;
} else if (![publicKeyPath isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKeyPath length] <= 0) {
return nil;
}
//获取公钥对象和需要加密的字符串内容编码数据流
SecKeyRef publicKeyRef = [self getPublicKeyRefWithFilePath:publicKeyPath];
NSData *originData = [originString dataUsingEncoding:NSUTF8StringEncoding];
if ([[self class] isEmptyKeyRef:(__bridge id)(publicKeyRef)]) {
return nil;
}
if ((originData == nil) || (originData == NULL)) {
return nil;
} else if (![originData isKindOfClass:[NSData class]]) {
return nil;
} else if ([originData length] <= 0) {
return nil;
}
//加密源字符串内容编码数据流的数据
NSData *resultData = nil;
resultData = [self encryptData:originData withKeyRef:publicKeyRef];
return [[self class] base64EncodedStringWithData:resultData];
}
+ (NSString *)decryptString:(NSString *)encryptString privateKeyPath:(NSString *)privateKeyPath privateKeyPwd:(NSString *)privateKeyPwd
{
//判断encryptString参数是否正确
if ((encryptString == nil) || (encryptString == NULL)) {
return nil;
} else if (![encryptString isKindOfClass:[NSString class]]) {
return nil;
} else if ([encryptString length] <= 0) {
return nil;
}
//判断publicKeyPath参数是否正确
if ((privateKeyPath == nil) || (privateKeyPath == NULL)) {
return nil;
} else if (![privateKeyPath isKindOfClass:[NSString class]]) {
return nil;
} else if ([privateKeyPath length] <= 0) {
return nil;
}
//判断密码是否存在
NSString *keyPassword = [NSString stringWithFormat:@"%@",privateKeyPwd];
if ((privateKeyPwd == nil) || (privateKeyPwd == NULL)) {
keyPassword = @"";
} else if (![privateKeyPwd isKindOfClass:[NSString class]]) {
keyPassword = @"";
} else if ([privateKeyPwd length] <= 0) {
keyPassword = @"";
}
//获取私钥对象和需要加密的字符串内容编码数据流
NSData *encryptData = nil, *decryptData = nil;
SecKeyRef privateKeyRef = [self getPrivateKeyRefWithFilePath:privateKeyPath
keyPassword:privateKeyPwd];
encryptData = [[self class] base64DecodeDataWithString:encryptString];
if ([[self class] isEmptyKeyRef:(__bridge id)(privateKeyRef)]) {
return nil;
}
if ((encryptData == nil) || (encryptData == NULL)) {
return nil;
} else if (![encryptData isKindOfClass:[NSData class]]) {
return nil;
} else if ([encryptData length] <= 0) {
return nil;
}
NSStringEncoding encoding = NSUTF8StringEncoding;
decryptData = [self decryptData:encryptData withKeyRef:privateKeyRef];
return [[NSString alloc] 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)) {
return nil;
} else if (![originData isKindOfClass:[NSData class]]) {
return nil;
} else if ([originData length] <= 0) {
return nil;
}
//判断publicKeyPath参数是否正确
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//获取需要加密的字符串内容编码数据流
SecKeyRef publicKeyRef = [self publicKeyRefWithPublicKey:publicKey];
if([[self class] isEmptyKeyRef:(__bridge id)(publicKeyRef)]){
return nil;
}
return [self encryptData:originData withKeyRef:publicKeyRef];
}
+ (NSString *)encryptString:(NSString *)originString publicKey:(NSString *)publicKey
{
//判断publicKey参数是否正确
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//判断originString参数是否正确
if ((originString == nil) || (originString == NULL)) {
return nil;
} else if (![originString isKindOfClass:[NSString class]]) {
return nil;
} else if ([originString length] <= 0) {
return nil;
}
//获取需要加密的字符串内容编码数据流
NSData *originData = nil, *encryptData = nil;
SecKeyRef publicKeyRef = [self publicKeyRefWithPublicKey:publicKey];
originData = [originString dataUsingEncoding:NSUTF8StringEncoding];
if([[self class] isEmptyKeyRef:(__bridge id)(publicKeyRef)]){
return nil;
}
if ((originData == nil) || (originData == NULL)) {
return nil;
} else if (![originData isKindOfClass:[NSData class]]) {
return nil;
} else if ([originData length] <= 0) {
return nil;
}
encryptData = [self encryptData:originData withKeyRef:publicKeyRef];
return [[self class] base64EncodedStringWithData:encryptData];
}
+ (NSString *)decryptString:(NSString *)encryptString privateKey:(NSString *)privateKey
{
//判断publicKey参数是否正确
if ((privateKey == nil) || (privateKey == NULL)) {
return nil;
} else if (![privateKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([privateKey length] <= 0) {
return nil;
}
//判断originString参数是否正确
if ((encryptString == nil) || (encryptString == NULL)) {
return nil;
} else if (![encryptString isKindOfClass:[NSString class]]) {
return nil;
} else if ([encryptString length] <= 0) {
return nil;
}
//获取私钥对象和需要加密的字符串内容编码数据流
SecKeyRef privateKeyRef;
NSData *encryptData = nil, *decryptData = nil;
privateKeyRef = [[self class] privateKeyRefWithPrivateKey:privateKey];
encryptData = [[self class] base64DecodeDataWithString:encryptString];
if ([[self class] isEmptyKeyRef:(__bridge id)(privateKeyRef)]) {
return nil;
}
if ((encryptData == nil) || (encryptData == NULL)) {
return nil;
} else if (![encryptData isKindOfClass:[NSData class]]) {
return nil;
} else if ([encryptData length] <= 0) {
return nil;
}
NSStringEncoding encoding = NSUTF8StringEncoding;
decryptData = [self decryptData:encryptData withKeyRef:privateKeyRef];
return [[NSString alloc] 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);
网友评论
1.假如我想在本地存储用户身份证、银行卡号及密码。应该选择哪种加密方式呢?
2.再延伸一下,上面的四种加密方式分别应用在什么场景下。
3.假如已经把用户的身份证、银行卡号及密码等敏感信息明文存到的NSUserDefault里面去了,使用in-house安装,如果是你,如何攻破我的app,拿到存在userdefault里面的敏感信息呢? 如何做可以防止拿到敏感信息。