之前的項目中接觸過一些加密的方法乏沸,也沒有太仔細的進行記錄和研究。最近在寫SDK
時美莫,加密模塊的占比相當之大页眯;借此時機,對我們常用的加密方式做一個筆記厢呵。
為什么要做加密操作窝撵?
加密就是為了保證我們的數(shù)據(jù)安全,即不被他人篡改或截取到有用的信息的操作襟铭。iOS
一直以安全著稱碌奉,但是從Xcode
的Ghost
事件之后,iOS
安全不可摧的神話似乎已經(jīng)被打破寒砖。事實證明赐劣,無論是Android
還是iOS
,該加密處理的還是需要加密處理哩都,誰也不能保證自己一定是安全的魁兼。下面我們來介紹iOS
常用到的加密方式。
iOS常用加密方式
常見的iOS代碼加密常用加密方式包括Base64加密
漠嵌、MD5加密
咐汞、AES加密
盖呼、RSA加密
等。無論選擇哪種加密算法化撕,最終都是為了保證代碼安全几晤,捍衛(wèi)自己的產(chǎn)品原創(chuàng)性。
Base64加密
Base64
編碼的思想是:采用64
個基本的ASCII碼
字符對數(shù)據(jù)進行重新編碼植阴。它將需要編碼的數(shù)據(jù)拆分成字節(jié)數(shù)組锌仅,以3
個字節(jié)為一組,按順序排列24
位數(shù)據(jù)墙贱,再把這24
位數(shù)據(jù)分成4
組热芹,即每組6
位;再在每組的的最高位前補兩個0
湊足一個字節(jié)惨撇,這樣就把一個3
字節(jié)為一組的數(shù)據(jù)重新編碼成了4
個字節(jié)伊脓;當所要編碼的數(shù)據(jù)的字節(jié)數(shù)不是3
的整倍數(shù),也就是說在分組時最后一組不夠3
個字節(jié)魁衙,這時在最后一組填充1
到2
個0
字節(jié)报腔,并在最后編碼完成后在結尾添加1
到2
個=
號。例如:將對ABC
進行Base64
編碼首先取ABC
對應的ASCII碼
值剖淀,A : 65
纯蛾、B : 66
、C : 67
纵隔,再取二進制值A : 01000001
翻诉、B : 01000010
、C : 01000011
捌刮,然后把這三個字節(jié)的二進制碼接起來010000010100001001000011
碰煌,再以6
位為單位分成4
個數(shù)據(jù)塊并在最高位填充兩個0
后形成4
個字節(jié)的編碼后的值00010000
、00010100
绅作、00001001
芦圾、00000011
;再把這4
個字節(jié)數(shù)據(jù)轉(zhuǎn)化成10進制數(shù)
得16
俄认、20
个少、19
、3
眯杏;最后根據(jù)Base64
給出的64
個基本字符表夜焦,查出對應的ASCII碼
字符Q
、U
役拴、J
糊探、D
钾埂,這里的值實際就是數(shù)據(jù)在字符表中的索引河闰。解碼過程就是把4
個字節(jié)再還原成3
個字節(jié)再根據(jù)不同的數(shù)據(jù)形式把字節(jié)數(shù)組重新整理成數(shù)據(jù)科平。注:Base64字符表,包括大寫A-Z
小寫a-z
數(shù)字0-9
和+
以及/
姜性。
Base64加密原則:6bit(原8bit)一個字節(jié)瞪慧,不足的位數(shù)用0補齊,兩個0用一個=表示部念。
Base64加密特點:
- 數(shù)據(jù)加密之后弃酌,數(shù)據(jù)量會變大,變大1/3左右儡炼。
- 可進行反向解密妓湘。
- 編碼后有個非常顯著的特點,末尾有個=號乌询。
在iOS中Base64加解密使用方法介紹(本例使用系統(tǒng)API榜贴,僅支持iOS7及以后的系統(tǒng)版本)
/****************************Base64.m類實現(xiàn)文件內(nèi)容****************************/
+ (NSString *)base64EncodedStringWithData:(NSData *)data
{
//判斷是否傳入需要加密數(shù)據(jù)參數(shù)
if ((data == nil) || (data == NULL)) {
return nil;
} else if (![data isKindOfClass:[NSData class]]) {
return nil;
}
//判斷設備系統(tǒng)是否滿足條件
if ([[[UIDevice currentDevice] systemVersion] doubleValue] <= 6.9) {
return nil;
}
//使用系統(tǒng)的API進行Base64加密操作
NSDataBase64EncodingOptions options;
options = NSDataBase64EncodingEndLineWithLineFeed;
return [data base64EncodedStringWithOptions:options];
}
+ (NSData *)base64DecodeDataWithString:(NSString *)string
{
//判斷是否傳入需要加密數(shù)據(jù)參數(shù)
if ((string == nil) || (string == NULL)) {
return nil;
} else if (![string isKindOfClass:[NSString class]]) {
return nil;
}
//判斷設備系統(tǒng)是否滿足條件
if ([[[UIDevice currentDevice] systemVersion] doubleValue] <= 6.9) {
return nil;
}
//使用系統(tǒng)的API進行Base64解密操作
NSDataBase64DecodingOptions options;
options = NSDataBase64DecodingIgnoreUnknownCharacters;
return [[NSData alloc] initWithBase64EncodedString:string options:options];
}
/*****************************************************************************/
//使用Base64文件進行Base64加密和解密
/*********************************使用Base64類*********************************/
//使用Base64執(zhí)行加密操作
NSString *string = @"abcdefghijklmnopqrstuvwxyz";
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodeString = [Base64 base64EncodedStringWithData:data];
NSLog(@"encodeString : %@", encodeString);
//使用Base64執(zhí)行解密操作
NSString *decodeString = nil;
NSData *decodeData = [Base64 base64DecodeDataWithString:encodeString];
decodeString = [[NSString alloc] initWithData:decodeData
encoding:NSUTF8StringEncoding];
NSLog(@"decodeString : %@", decodeString);
/******************************************************************************/
MD5加密(MD5是一種摘要,而非加密妹田,只是經(jīng)常與加密配合使用)
MD5
的全稱是Message-DigestAlgorithm 5
唬党,Message-Digest
泛指字節(jié)串(Message
)的Hash
變換,就是把一個任意長度的字節(jié)串
變換成一定長的大整數(shù)鬼佣。請注意我使用了字節(jié)串
而不是字符串
這個詞驶拱,是因為這種變換只與字節(jié)的值有關,與字符集或編碼方式無關晶衷。MD5
將任意長度的字節(jié)串
變換成一個128bit
的大整數(shù)蓝纲,并且它是一個不可逆的字符串變換算法,換句話說就是晌纫,即使你看到源程序和算法描述驻龟,也無法將一個MD5
的值變換回原始的字符串,從數(shù)學原理上說缸匪,是因為原始的字符串有無窮多個翁狐,這有點象不存在反函數(shù)的數(shù)學函數(shù)。MD5
的典型應用是對一段Message
(字節(jié)串)產(chǎn)生fingerprint
(指紋)凌蔬,以防止被"篡改"露懒。舉個例子,你將一段話寫在一個叫readme.txt
文件中砂心,并對這個readme.txt
產(chǎn)生一個MD5
的值并記錄在案懈词,然后你可以傳播這個文件給別人,別人如果修改了文件中的任何內(nèi)容辩诞,你對這個文件重新計算MD5
時就會發(fā)現(xiàn)坎弯。如果再有一個第三方的認證機構,用MD5
還可以防止文件作者的"抵賴",這就是所謂的數(shù)字簽名應用抠忘。MD5
還廣泛用于加密和解密技術上撩炊,在很多操作系統(tǒng)中,用戶的密碼是以MD5
值(或類似的其它算法)的方式保存的崎脉,用戶Login
的時候拧咳,系統(tǒng)是把用戶輸入的密碼計算成MD5
值,然后再去和系統(tǒng)中保存的MD5
值進行比較囚灼,而系統(tǒng)并"不知道"用戶的密碼是什么骆膝。MD5加密大體都應用在:驗證數(shù)據(jù)或文件一致性、數(shù)字簽名灶体、安全訪問認證等等阅签。大概可比喻為:人的指紋來理解。
注:MD5
加密是不可逆的蝎抽,也就是說愉择,MD5
加密后是不能解密的,所謂的解密只是用大數(shù)據(jù)的”試用”织中,來測出結果的锥涕。
MD5特點:
- 壓縮性 : 任意長度的數(shù)據(jù),算出的MD5值長度都是固定的。
- 容易計算 : 從原數(shù)據(jù)計算出MD5值很容易狭吼。
- 抗修改性 : 對原數(shù)據(jù)進行任何改動层坠,哪怕只修改一個字節(jié),所得到的MD5值都有很大區(qū)別刁笙。
- 弱抗碰撞 : 已知原數(shù)據(jù)和其MD5值破花,想找到一個具有相同MD5值的數(shù)據(jù)(即偽造數(shù)據(jù))是非常困難的。
- 強抗碰撞 : 想找到兩個不同數(shù)據(jù)疲吸,使他們具有相同的MD5值座每,是非常困難的。
在iOS中MD5加密和驗簽使用方法介紹
/****************************MD5.m類實現(xiàn)文件內(nèi)容****************************/
//對字符串數(shù)據(jù)進行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];
}
//對二進制數(shù)據(jù)進行MD5的簽名
+ (NSData *)md5SignWithData:(NSData *)data
{
Byte byte[CC_MD5_DIGEST_LENGTH]; //定義一個字節(jié)數(shù)組來接收結果
CC_MD5((const void*)([data bytes]), (CC_LONG)[data length], byte);
return [NSData dataWithBytes:byte length:CC_MD5_DIGEST_LENGTH];
}
/******************************************************************************/
//使用MD5文件進行MD5加密和驗簽
/*********************************使用MD5類*********************************/
//使用MD5執(zhí)行加密操作
NSString *string2 = @"abcdefghijklmnopqrstuvwxyz";
NSString *encodeString2 = [MD5 md5SignWithString:string2];
NSLog(@"encodeString2 : %@", encodeString2);
//MD5為不可逆的操作摘悴,使用MD5執(zhí)行驗簽操作
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加密法
,是美國聯(lián)邦政府采用的一種區(qū)塊加密標準蹂喻。它是一種對稱加密算法葱椭,這個標準也替代原先的DES標準,已經(jīng)被多方分析且廣為全世界所使用口四。AES設計有三個密鑰長度:128孵运、192、256位蔓彩,相對而言治笨,AES的128密鑰比DES的56密鑰強1021倍驳概。AES算法主要包括三個方面:輪變化、圈數(shù)和密鑰擴展旷赖∷秤郑總體來說,AES作為新一代的數(shù)據(jù)加密標準匯聚了強安全性杠愧、高性能、高效率逞壁、易用和靈活流济,在軟件及硬件上都能快速地加解密且只需要很少的存儲資源等優(yōu)點。
AES加密流程介紹無從下筆腌闯,直接上圖了绳瘟。
AES加解密特點:
- AES強安全性、高性能姿骏、高效率糖声、易用和靈活。
- 在軟件及硬件上都能快速地加解密且只需要很少的存儲資源分瘦。
在iOS中AES加解密的實現(xiàn)介紹
//需要導入:#import <CommonCrypto/CommonCrypto.h>庫才能使用
/**
* AES128 + ECB + PKCS7
* @param data 要加密的原始數(shù)據(jù)
* @param key 加密 key
* @return 加密后數(shù)據(jù)
*/
+ (NSData *)encryptData:(NSData *)data key:(NSData *)key
{
//判斷解密的流數(shù)據(jù)是否存在
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 要解密的原始數(shù)據(jù)
* @param key 解密 key
* @return 解密后數(shù)據(jù)
*/
+ (NSData *)decryptData:(NSData *)data key:(NSData *)key
{
//判斷解密的流數(shù)據(jù)是否存在
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執(zhí)行加密操作
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執(zhí)行解密操作
NSString *decodeString3 = nil;
NSData *decodeData3 = [AESEncrypt decryptData:encodeData3
key:keyData3];
decodeString3 = [[NSString alloc] initWithData:decodeData3
encoding:NSUTF8StringEncoding];
NSLog(@"decodeString3 : %@", decodeString3);
RSA加密
RSA是目前最有影響力的公鑰加密算法蘸泻,它能夠抵抗到目前為止已知的絕大多數(shù)密碼攻擊,已被ISO推薦為公鑰數(shù)據(jù)加密標準嘲玫。RSA的公開密鑰密碼體制就是使用不同的加密密鑰與解密密鑰悦施,是一種“由已知加密密鑰推導出解密密鑰在計算上是不可行的”密碼體制。通常是先生成一對RSA密鑰去团,其中之一是保密密鑰抡诞,由用戶保存;另一個為公開密鑰土陪,可對外公開昼汗,甚至可在網(wǎng)絡服務器中注冊。為提高保密強度鬼雀,RSA密鑰至少為500位長顷窒,一般推薦使用1024位,這就使加密的計算量很大源哩。為減少計算量蹋肮,在傳送信息時,常采用傳統(tǒng)加密方法與公開密鑰加密方法相結合的方式璧疗,即信息采用改進的DES或IDEA對話密鑰加密坯辩,然后使用RSA密鑰加密對話密鑰和信息摘要,對方收到信息后崩侠,用不同的密鑰解密并可核對信息摘要漆魔。RSA算法是第一個能同時用于加密和數(shù)字簽名的算法,也易于理解和操作,RSA是被研究得最廣泛的公鑰算法改抡。RSA算法是一種非對稱密碼算法矢炼,所謂非對稱,就是指該算法需要一對密鑰阿纤,使用其中一個加密句灌,則需要用另一個才能解密。RSA加密大體都應用在:本地數(shù)據(jù)加密欠拾、網(wǎng)絡傳輸數(shù)據(jù)加密胰锌、方法體和方法名高級混淆以及程序結構混排加密。例如:對客戶端傳輸數(shù)據(jù)提供加密方案藐窄,有效防止通過網(wǎng)絡接口的攔截獲取资昧。
RSA的算法涉及三個參數(shù),n荆忍、e1格带、e2。其中刹枉,n是兩個大質(zhì)數(shù)p叽唱、q的積,n的二進制表示時所占用的位數(shù)微宝,就是所謂的密鑰長度尔觉。e1和e2是一對相關的值,e1可以任意取芥吟,但要求e1與(p-1)(q-1)互質(zhì)侦铜;再選擇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安全性很高萎胰,能夠抵抗到目前為止已知的絕大多數(shù)密碼攻擊。
在線生成RSA密鑰對的網(wǎng)址:在線生成非對稱加密公鑰私鑰對等豆胸,RSA密鑰格式請使用PKCS#8格式奥洼。PKCS#1與PKCS#8的區(qū)別還待后續(xù)查閱資料巷疼,再進行補充記錄晚胡。
在iOS中RSA加解密的實現(xiàn)介紹(支持密鑰文件<.pem>和字符串密鑰)
/****************************RSAEncrypt.m類實現(xiàn)文件內(nèi)容****************************/
#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
{
//讀取私鑰證書文件的內(nèi)容
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;
}
//拼接密碼參數(shù)到字典中
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
{
//判斷參數(shù)是否正確
if ((privateKey == nil) || (privateKey == NULL)) {
return nil;
} else if (![privateKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([privateKey length] <= 0) {
return nil;
}
//解析私鑰對象內(nèi)容
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
{
//讀取公鑰證書文件的內(nèi)容
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
{
//判斷參數(shù)是否正確
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//解析公鑰對象內(nèi)容
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參數(shù)是否正確
if ((originString == nil) || (originString == NULL)) {
return nil;
} else if (![originString isKindOfClass:[NSString class]]) {
return nil;
} else if ([originString length] <= 0) {
return nil;
}
//判斷publicKeyPath參數(shù)是否正確
if ((publicKeyPath == nil) || (publicKeyPath == NULL)) {
return nil;
} else if (![publicKeyPath isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKeyPath length] <= 0) {
return nil;
}
//獲取公鑰對象和需要加密的字符串內(nèi)容編碼數(shù)據(jù)流
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;
}
//加密源字符串內(nèi)容編碼數(shù)據(jù)流的數(shù)據(jù)
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參數(shù)是否正確
if ((encryptString == nil) || (encryptString == NULL)) {
return nil;
} else if (![encryptString isKindOfClass:[NSString class]]) {
return nil;
} else if ([encryptString length] <= 0) {
return nil;
}
//判斷publicKeyPath參數(shù)是否正確
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 = @"";
}
//獲取私鑰對象和需要加密的字符串內(nèi)容編碼數(shù)據(jù)流
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參數(shù)是否正確
if ((originData == nil) || (originData == NULL)) {
return nil;
} else if (![originData isKindOfClass:[NSData class]]) {
return nil;
} else if ([originData length] <= 0) {
return nil;
}
//判斷publicKeyPath參數(shù)是否正確
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//獲取需要加密的字符串內(nèi)容編碼數(shù)據(jù)流
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參數(shù)是否正確
if ((publicKey == nil) || (publicKey == NULL)) {
return nil;
} else if (![publicKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([publicKey length] <= 0) {
return nil;
}
//判斷originString參數(shù)是否正確
if ((originString == nil) || (originString == NULL)) {
return nil;
} else if (![originString isKindOfClass:[NSString class]]) {
return nil;
} else if ([originString length] <= 0) {
return nil;
}
//獲取需要加密的字符串內(nèi)容編碼數(shù)據(jù)流
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參數(shù)是否正確
if ((privateKey == nil) || (privateKey == NULL)) {
return nil;
} else if (![privateKey isKindOfClass:[NSString class]]) {
return nil;
} else if ([privateKey length] <= 0) {
return nil;
}
//判斷originString參數(shù)是否正確
if ((encryptString == nil) || (encryptString == NULL)) {
return nil;
} else if (![encryptString isKindOfClass:[NSString class]]) {
return nil;
} else if ([encryptString length] <= 0) {
return nil;
}
//獲取私鑰對象和需要加密的字符串內(nèi)容編碼數(shù)據(jù)流
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執(zhí)行加密操作
NSString *string4 = @"abcdefghijklmnopqrstuvwxyz";
NSString *encodeString4 = [RSAEncrypt encryptString:string4
publicKey:mPublicKey];
NSLog(@"encodeString4 : %@", encodeString4);
//使用RSA執(zhí)行解密操作
NSString *decodeString4 = [RSAEncrypt decryptString:encodeString4
privateKey:mPrivateKey];
NSLog(@"decodeString4 : %@", decodeString4);