I would like to secure my data so I try to encrypt it with XXTEA. I do this way:
- inputString -> XXTEA encrypt -> outputString
- outputString -> XXTEA decrypt -> inputString
Everything is encrypt and decrypt ok. But when I try to make a base64 encode the output after XXTEA encrypt it and base64 decode it before XXTEA decrypt, the result is wrong:
- input -> XXTEA encrypt -> base64 encode -> output
- output -> base64 decode -> XXTEA decrypt != input
When I test with http://www.tools4noobs.com/online_tools/xxtea_encrypt/ and http://www.tools4noobs.com/online_tools/xxtea_decrypt/
My example's input string is hello
and its final result is bjz/S2f3Xkxr08hu
But when I test with my code (see below), the final result is bjz/Sw==
Here is my 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;
}
Here is my 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;
}
Do you know what is wrong with my code? Any help would be appreciated! Thanks very much.