最近專案中對接微軟小冰的業務,大廠都對內部的資源有相當的保密措施,對給到第三方的資料都是加密的,下面是應用到的相關的加密解密函式:異或加密解密及base64的加密解密
異或加密演算法
static NSString *secretKey =@"XiaoBing_Qitianzhen";
/**
* 異或加密演算法
*
* @param sourceData 需要加密的位元組流
* @param key 加密的key
*
* @return 加密後的位元組流
*/
- (NSString *)encryptForPlainText:(NSString *)plainText
{
//儲存加密後的字元
NSMutableString *encryption=[NSMutableString string];
//編碼轉換後的字串 UTF_8->iso-8859-1
NSString *encoding=[[NSString alloc]initWithData:[plainText dataUsingEncoding:NSUTF8StringEncoding] encoding:NSISOLatin1StringEncoding];
for(int i=0,j=0;i<encoding.length;i++,j++){
if(j==secretKey.length){
j=0;
}
//異或後的字元
char cipher=(char)([encoding characterAtIndex:i]^[secretKey characterAtIndex:j]);
//NSLog(@"%c轉成16進位制的字串:%@,%@",cipher,[NSString stringWithFormat:@"%hhx",cipher],[NSString stringWithFormat:@"%x",cipher&0xff]);
//轉成16進位制形式的字串 \x8b轉成8b字串
NSString *strCipher= [NSString stringWithFormat:@"%hhx",cipher];
if(strCipher.length == 1){
[encryption appendFormat:@"0%@",strCipher];
}else{
[encryption appendString:strCipher];
}
}
return encryption;
}
複製程式碼
異或解密
- (NSString *)decryptForEncryption:(NSString *)encryption {
//儲存解密後的字元
NSMutableString *decryption=[NSMutableString string];
//解碼字元
NSString *decoding=nil;
for(int i=0,j=0;i<encryption.length/2;i++,j++){
if(j==secretKey.length){
j=0;
}
//擷取16進位制形式的字串 \x8b中的8b
NSString *tem=[encryption substringWithRange:NSMakeRange(i*2, 2)];
char *endptr;
//把16進位制形式的字串轉為字元
char n=(char)(int)strtoul([tem UTF8String],&endptr,16);
//判斷是否為加密字元
if (n=='\0'&&*endptr!='\0') {
[decryption setString:@""];
break;
}
[decryption appendFormat:@"%c",(char)(n^[secretKey characterAtIndex:j])];
}
if (![decryption isEqualToString:@""]) {
//編碼後的字串 iso-8859-1 -> UTF_8
decoding=[[NSString alloc]initWithData:[[decryption copy] dataUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
}
if (decoding==nil) {
decoding=encryption;
}
return decoding;
}
複製程式碼
base64的加密解密
//把字串轉成Base64編碼
- (NSString *)base64EncodeString:(NSString *)string
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [data base64EncodedStringWithOptions:0];
}
//字串解碼
- (NSString *)stringEncodeBase64:(NSString *)encodeStr
{
NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:encodeStr options:0];
NSString *base64Decoded = [[NSString alloc]initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
return base64Decoded;
}
複製程式碼
此文只為記錄筆記,以後查閱方便!有哪些寫的不對的地方,歡迎指正!!!