Reputation:
Today, i try convert xor encryption java code to c++ but is not working and output wrong, maybe something i wrong, java code:
public static String encryptDecryptStr(String str) {
String key = "ABCDEF";
final int l0 = key.length() - 1;
int l1 = key.length() - 1;
final char[] strRemp = new char[str.length()];
char opcode = 85;;
for (int i = strRemp.length - 1; i >= 0; i--) {
strRemp[i] = (char) (str.charAt(i) ^ opcode ^ key.charAt(l1));
opcode = (char) ((char) (opcode ^ i ^ key.charAt(l1)) & 63);
--l1;
if (l1 < 0) l1 = l0;
}
return new String(strRemp);}
i try c++ code:
JNIEXPORT jstring JNICALL Java_com_test_app_Utils_encryptDecryptStr(JNIEnv *env, jobject, jstring inStr){
std::string in = env->GetStringUTFChars(inStr, NULL);
std::string key = "ABCDEF";
int l0 = static_cast<int>(key.size() - 1);
int l1 = static_cast<int>(key.size() - 1);
char *strRemp = new char[in.size()];
char opcode = 85;
for (int i = static_cast<int>(strlen(strRemp) - 1); i >= 0; i--) {
strRemp[i] = in[i] ^ opcode ^ key[l1];
opcode = static_cast<char >(static_cast<char >(opcode ^ i ^ key[l1]) & 63);
--l1;
if (l1 < 0) l1 = l0;
}
return (jstring)env->NewStringUTF(strRemp);}
i test:
com.test.app.Utils.encryptDecryptStr(encryptDecryptStr("Hello World"));
test 2nd:
encryptDecryptStr(com.test.app.Utils.encryptDecryptStr("Hello World"));
some one can help me?
Upvotes: 0
Views: 123
Reputation: 8598
char
in Java and char
in C++ are two different types.In Java you are working with 2 byte UTF-16 encoded characters. In C++ you are working with 1 byte characters, but they are actually multibyte UTF-8 encoded. (See also the docs for GetStringUTFChars.) You must make sure that you are working with the same binary data.
int i = static_cast<int>(strlen(strRemp) - 1)
This is undefined behavior, because you haven't properly 0-terminated strRemp
. You should use in.size()
instead.
std::string in = env->GetStringUTFChars(inStr, NULL);
This creates a memory leak, because the std::string
constructor copies the data from the char* array returned by GetStringUTFChars
, but that array itself is never freed.
You don't delete[] strRemp
at the end, another memory leak.
You shouldn't use strings
for such binary data, as string functions will parse all bytes as characters in whatever encoding they think the string has, making your code break at best or introduce serious security issues at worst. Work with raw binary data arrays instead.
Upvotes: 3