【发布时间】:2017-05-15 18:48:21
【问题描述】:
我正在尝试使用 JNI 将字符串从 C 发送到 Java。 这是我的 C 代码:
static char* test_encrypt_ecb_verbose(char* plain_text_char, char* key_char, char** ciphertext)
{
uint8_t i, buf[64], buf2[64];
uint8_t key[16];
// 512bit text
uint8_t plain_text[64];
char outstr[64];
memcpy(key,key_char,16) ;
memcpy(plain_text, plain_text_char, 64);
memset(buf, 0, 64);
memset(buf2, 0, 64);
// print text to encrypt, key and IV
printf("ECB encrypt verbose:\n\n");
printf("plain text:\n");
for(i = (uint8_t) 0; i < (uint8_t) 4; ++i)
{
phex(plain_text + i * (uint8_t) 16);
}
printf("\n");
printf("key:\n");
phex(key);
printf("\n");
// print the resulting cipher as 4 x 16 byte strings
printf("ciphertext:\n");
for(i = 0; i < 4; ++i)
{
AES128_ECB_encrypt(plain_text + (i*16), key, buf+(i*16));
//phex(buf + (i * 16));
for (int j = 0; j < 16; ++j){
printf("%c", (buf + (i * 16))[j]);
}
printf("\n");
}
printf("\n\n decrypted text:\n");
for (i = 0; i < 4; ++i)
{
AES128_ECB_decrypt(buf + (i * 16), key, plain_text + (i * 16));
phex(plain_text + (i * 16));
}
printf("\n\n\n");
*ciphertext = malloc(64);
memcpy(*ciphertext, buf, 64);
return outstr;
JNIEXPORT jstring JNICALL Java_JniApp_test
(JNIEnv *env, jobject obj, jstring inputstr, jstring keystr){
const char *str;
const char *kstr;
char* encstr=NULL,estr;
str = (*env)->GetStringUTFChars(env,inputstr,NULL);
kstr = (*env)->GetStringUTFChars(env,keystr,NULL);
estr = test_encrypt_ecb_verbose(str,kstr,&encstr);
printf("---Start---\n");
//int b = test(num);
for (int j = 0; j < 64; ++j){
printf("%c",encstr[j]);
}
//printf("test: %c", *encstr);
return(*env)->NewStringUTF(env,encstr);
}
当我在返回 java.. 之前打印 encstr 时,我得到了这个:
)Ñi‰ªGÀ6Btílt~,²#úK23Ej•)Ñi‰ªGÀ6Btílt~,²#úK23Ej•
但是当我将它发送到 Java 并打印时,我没有得到相同的字符串。
这是我的 Java 文件:
public class JniApp {
public native String test(String inputstr, String keystr);
public static void main(String args[]){
JniApp ja = new JniApp();
String j = ja.test("1234567890abffff0987654321fedcba1234567890abffff0987654321fedcba","fred789lk6n2q7b1");
System.out.println("This is the cipher text\n"+j);
}
static
{
System.loadLibrary("editjnib");
}
}
如何在 Java 中也获得相同的字符串?我有什么做错了吗?
【问题讨论】:
-
看看这里:jnicookbook.owsiak.org/recipe-No-009 和这里jnicookbook.owsiak.org/recipe-No-010 这些示例展示了如何来回发送字符串。玩 JNI!
标签: java c string java-native-interface