异或
异或运算:运算符为 “ ^ ”
定义:同则假,异则真。(1 ^ 1得 0,1 ^ 0得 1)
// 异或加密
- (NSData *)xor_encrypt:(NSData*)data{
//加密得私钥
NSString const *privateKey = @"asdffgjlfdsjglf123fdgfdg";
// 获取key的长度
NSInteger length = privateKey.length;
// 将OC字符串转换为C字符串
const char *keys = [privateKey cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cKey[length];
//memcpy函数的功能是从源内存地址的起始位置开始拷贝若干个字节到目标内存地址中
memcpy(cKey, keys, length);
// 数据初始化,空间未分配 配合使用 appendBytes
NSMutableData *encryptData = [[NSMutableData alloc] initWithCapacity:length];
// 获取字节指针
const Byte *point = data.bytes;
for (int i = 0; i < data.length; i++) {
// 算出当前位置字节,要和密钥的异或运算的密钥字节
int l = i % length;
char c = cKey[l];
// 异或运算
Byte b = (Byte) ((point[i]) ^ c);
// 追加字节
[encryptData appendBytes:&b length:1];
}
return encryptData.copy;
}
//测试加密
-(void)test{
//=======测试===========
//需要加密得内容
NSString*string = @"123456";
NSLog(@"原始字符串:%@",string);
//进行加密
NSData*data = [string dataUsingEncoding:NSUTF8StringEncoding];
data = [self xor_encrypt:data];
NSString*enstring = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//输出加密后得字符串
NSLog(@"加密后得字符串:%@",enstring);
//解密
NSData*data2 = [enstring dataUsingEncoding:NSUTF8StringEncoding];
data2 = [self xor_encrypt:data2];
NSString*destring = [[NSString alloc]initWithData:data2 encoding:NSUTF8StringEncoding];
//输出解密后得字符串
NSLog(@"解密后得字符串:%@",destring);
//=======测试 end===========
}
//测试得输出:
2018-12-26 10:25:53.657799+0800 M[1553:36230]原始字符串:123456�
2018-12-26 10:25:53.657799+0800 M[1553:36230]加密后得字符串:PAWRSQ�
2018-12-26 10:25:53.657916+0800 M[1553:36230]解密后得字符串:123456