I am trying to send string from C to Java using JNI. Here is my C code:
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);
}
When I print encstr before return back to java.. I get this:
)Ñi‰ªGÀ6Btílt˜,²#úK23Ej•)Ñi‰ªGÀ6Btílt˜,²#úK23Ej•
But when I send this to Java and print, I dont get the same string.
Here is my Java file:
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");
}
}
How can I get the same string in Java also? I there anything I am doing wrong?