我想保护我的数据,所以我尝试使用 XXTEA 对其进行加密。我这样做:
- inputString -> XXTEA 加密 -> outputString
- outputString -> XXTEA 解密 -> inputString
一切都是加密和解密好的。但是当我尝试在 XXTEA 加密后对输出进行 base64 编码并在 XXTEA 解密之前对其进行 base64 解码时,结果是错误的:
- 输入 -> XXTEA 加密 -> base64 编码 -> 输出
- 输出 -> base64 解码 -> XXTEA 解密!= 输入
当我使用http://www.tools4noobs.com/online_tools/xxtea_encrypt/和http://www.tools4noobs.com/online_tools/xxtea_decrypt/进行测试时
我的例子的输入字符串是hello
,它的最终结果是bjz/S2f3Xkxr08hu
但是当我用我的代码进行测试时(见下文),最终结果是bjz/Sw==
这是我的encryption code
:
std::string ProjectUtils::encrypt_data_xxtea(std::string input, std::string secret) {
//Encrypt with XXTEA
xxtea_long retLength = 0;
unsigned char data[input.length()];
strncpy((char*)data, input.c_str(), sizeof(data));
xxtea_long dataLength = (xxtea_long) sizeof(data);
unsigned char key[secret.length()];
strncpy((char*)key, secret.c_str(), sizeof(key));
xxtea_long keyLength = (xxtea_long) sizeof(key);
unsigned char *encryptedData = xxtea_encrypt(data, dataLength, key, keyLength, &retLength);
//Encode base64
char* out = NULL;
base64Encode(encryptedData, sizeof(encryptedData), &out);
CCLOG("xxtea encrypted data: %s", out);
return out;
}
这是我的decryption code
:
char* ProjectUtils::decrypt_data_xxtea(std::string input, std::string secret) {
//Decode base64
unsigned char* output = NULL;
base64Decode((unsigned char*)input.c_str(), (unsigned int)strlen(input.c_str()), &output);
xxtea_long dataLength = (xxtea_long) sizeof(output);
xxtea_long retLength = 0;
unsigned char key[secret.length()];
strncpy((char*)key, secret.c_str(), sizeof(key));
xxtea_long keyLength = (xxtea_long) sizeof(key);
//Decrypt with XXTEA
char *decryptedData = reinterpret_cast<char*>(xxtea_decrypt(output, dataLength, key, keyLength, &retLength));
CCLOG("xxtea decrypted data: %s", decryptedData);
return decryptedData;
}
你知道我的代码有什么问题吗?任何帮助,将不胜感激!非常感谢。