方法1:
// 加密
-(NSString *)obfuscate:(NSData *)string withKey:(NSString *)key
{
NSData *data = string;
char *dataPtr = (char *) [data bytes];
char *keyData = (char *) [[key dataUsingEncoding:NSUTF8StringEncoding] bytes];
char *keyPtr = keyData;
int keyIndex = 0;
for (int x = 0; x < [data length]; x++){
*dataPtr = *dataPtr++ ^ *keyPtr++;
if (++keyIndex == [key length]) keyIndex = 0, keyPtr = keyData;
}
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
//解密
-(NSString*)encodeString:(NSString*)data :(NSString*)key
{
NSString *result=[NSString string];
for(int i=0; i < [data length]; i++){
int chData = [data characterAtIndex:i];
for(int j=0;j<[key length];j++){
int chKey = [key characterAtIndex:j];
chData = chData^chKey;
}
result=[NSString stringWithFormat:@"%@%@",result,[NSString stringWithFormat:@"%c",chData]];
}
return result;
}
方法2:
// 客户端内置私钥 static NSString const *privateKey = @"jwef37c9111210854f5986fc9ebb5548b2ae"; // 加密 - (NSData *)xor_encrypt { // 获取key的长度 NSInteger length = privateKey.length; // 将OC字符串转换为C字符串 const char *keys = [privateKey cStringUsingEncoding:NSASCIIStringEncoding]; unsigned char cKey[length]; memcpy(cKey, keys, length); // 数据初始化,空间未分配 配合使用 appendBytes NSMutableData *encryptData = [[NSMutableData alloc] initWithCapacity:length]; // 获取字节指针 const Byte *point = self.bytes; for (int i = 0; i < self.length; i++) { int l = i % length; // 算出当前位置字节,要和密钥的异或运算的密钥字节 char c = cKey[l]; Byte b = (Byte) ((point[i]) ^ c); // 异或运算 [encryptData appendBytes:&b length:1]; // 追加字节 } return encryptData.copy; } @end
// 解密
- (NSData *)xor_decrypt { return [self xor_encrypt]; }