今天,我尝试将 xor 加密 java 代码转换为 c++ 但不起作用并输出错误,也许我错了,java 代码: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);}我尝试 C++ 代码: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);}我测试:com.test.app.Utils.encryptDecryptStr(encryptDecryptStr("Hello World"));测试二:encryptDecryptStr(com.test.app.Utils.encryptDecryptStr("Hello World"));有人可以帮助我吗?
1 回答
达令说
TA贡献1821条经验 获得超6个赞
Java 和 C++ 是不同的语言。
char
在 Java 和char
C++ 中是两种不同的类型。
在 Java 中,您正在使用 2 字节的 UTF-16 编码字符。在 C++ 中,您使用的是 1 字节字符,但它们实际上是多字节 UTF-8 编码的。您必须确保使用相同的二进制数据。
int i = static_cast<int>(strlen(strRemp) - 1)
这是未定义的行为,因为您没有正确地 0-terminatedstrRemp
。你应该in.size()
改用。std::string in = env->GetStringUTFChars(inStr, NULL);
这会造成内存泄漏,因为std::string
构造函数从 返回的 char* 数组中复制数据GetStringUTFChars
,但该数组本身永远不会被释放。你
delete[] strRemp
最后没有,另一个内存泄漏。您不应该使用
strings
此类二进制数据,因为字符串函数会将所有字节解析为他们认为字符串具有的任何编码的字符,最好的情况是使您的代码中断,或者最坏的情况是引入严重的安全问题。而是使用原始二进制数据数组。
添加回答
举报
0/150
提交
取消