我有一个使用JNI的简单加密程序(JAVA,C++。简而言之:我将一个简单的字符串传递给 C++ 程序。C++ 程序为我加密该字符串并返回密码字符串。我将为客户端打印密文。
问题:当我在 c++ 中加密并将其传递给 java 时,某些字符无法传输。但是当我使用 c++ 控制台打印它时,它是正确的。该字符之一是:
ü
C++ 控制台中的密文:
ozmzâx~w|(~i}|64ío(üuvt*po~,s|*nY|(yy~(ktztskk|sgX
在java中传输的密文:
ozmz?x~w|(~i}|64ío(?uvt*po~,s|*nY|(yy~(ktztskk|sgX
(a , ü 丢失)
因此,由于这个错误,当我想解密文本时,这些字符无法正确解密(但在 c++ 中解密正确!)
纯文本 :
您好,这是加密器测试的测试消息,我们将为我们的应用程序测试它
密文java:
rmvpy4*Prq},s u~m}x uos}iqi rybozmz?x~w|(~i}|64ᄀo(?uvt po~,s|*nY|(yy| (ktztskk|sgX
解密文本:
您好,这是一个 encrケptor test 的测试消息,キe キ将为我们的应用程序测试它
(在“加密器”、“我们”和“将”中失败)我该怎么办?
我以 jbyteArray 格式将字符从 c++ 传输到 java。
C++ 代码:
JNIEXPORT jbyteArray JNICALL Java_com_mf_dems_HelloJNI_encryptTest
(JNIEnv *env, jobject thisObject, jobject encryptorContext, jstring
jInputBlock)
{
//get class
jclass encryptorContextClass = env->GetObjectClass(encryptorContext);
//get keyLength
jfieldID keyLengthFieldId = env->GetFieldID(encryptorContextClass,
"keyLength", "I");
jint keyLength = env->GetIntField(encryptorContext, keyLengthFieldId);
//get blockLength
jfieldID blockLengthFieldId = env->GetFieldID(encryptorContextClass,
"blockLength", "I");
jint blockLength = env->GetIntField(encryptorContext, blockLengthFieldId);
//get key
jfieldID keyFieldId = env->GetFieldID(encryptorContextClass, "key", "[C");
jobject jKeyArray =env->GetObjectField(encryptorContext, keyFieldId);
jchar *key =env->GetCharArrayElements((jcharArray)(jKeyArray), NULL);
//get inputBlock
const jchar *inputBlock = env->GetStringChars(jInputBlock, NULL);
jbyte *buf = new jbyte[blockLength];
unsigned int i=0;
for(i ; i< blockLength ; i++)
{
buf[i] =((inputBlock[i] +10) ^ key[i] ^ key[i+15] ^ 0x11);
}
env->ReleaseStringChars(jInputBlock, inputBlock);
env->ReleaseCharArrayElements((jcharArray)(jKeyArray), key, 0);
jbyteArray jOut = env->NewByteArray(blockLength);
env->SetByteArrayRegion(jOut, 0, blockLength, buf);
delete [] buf;
return jOut;
}
JAVA代码:
EncryptorContext encryptorContext = new EncryptorContext();
encryptorContext.setBlockLength(17);
encryptorContext.setKeyLength(32);
encryptorContext.setKey(new char[encryptorContext.getKeyLength()]);
String plainText = "Hello, This is a test message for encryptor test, we will test it for our application.";
String cipherText = "";
//set key
for (int i = 0; i < encryptorContext.getKeyLength(); i++) {
encryptorContext.getKey()[i] = (char) (i + 1);
}
//ENCRYPT
for (int i = 0; i < (plainText.length() -encryptorContext.getBlockLength()); i +encryptorContext.getBlockLength())
{
byte [] out = helloJNI.encryptTest(encryptorContext,
plainText.substring(i, i + encryptorContext.getBlockLength()));
byte[] latin1 = new String(out, "ISO-8859-1").getBytes("UTF-8");
for (byte b : out) {
cipherText+=(char)b;
}
}
System.out.println(cipherText);