Base64编码XXTEA加密字符串错误

时间:2015-03-19 10:19:31

标签: c++ base64 cocos2d-x xxtea

我想保护我的数据,所以我尝试用XXTEA加密它。我这样做:

  • inputString - > XXTEA加密 - > outputString
  • outputString - > XXTEA解密 - > inputString

所有内容都加密并解密。但是当我尝试在XXTEA加密后对其进行base64编码输出,并在XXTEA解密之前对base64进行解码,结果是错误的:

  • 输入 - > XXTEA加密 - > base64编码 - >输出
  • 输出 - > base64 decode - > 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;

}

你知道我的代码有什么问题吗?任何帮助,将不胜感激! 非常感谢。

2 个答案:

答案 0 :(得分:1)

这是cocos2d-x 3.4上的完整工作代码

coordinates.length

答案 1 :(得分:0)

感谢您的代码,它适用于我)

我已经用实际的retLength替换了base64字符串的长度

base64Encode(encryptedData, retLength, &out);

然后回来,获得实际尺寸

int outLength = cocos2d::base64Decode((unsigned char*)revertStr.c_str(), (unsigned int)strlen(revertStr.c_str()), &output);
char *decryptedData = reinterpret_cast<char*>(xxtea_decrypt(output, outLength, key, keyLength, &retLength));