最近项目中对接微软小冰的业务,大厂都对内部的资源有相当的保密措施,对给到第三方的数据都是加密的,下面是应用到的相关的加密解密函数:异或加密解密及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
异或解密
- (NSString *)decryptForEncryption:(NSString *)encryption { //保存解密后的字符 NSMutableString *decryption=[NSMutableString string]; //解码字符 NSString *decoding=nil; for(int i=0,j=0;iUTF_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;}复制代码
此文只为记录笔记,以后查阅方便!有哪些写的不对的地方,欢迎指正!!!