无法在JNI中编码为UTF-8 [英] Cannot encode to UTF-8 in JNI

查看:281
本文介绍了无法在JNI中编码为UTF-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回使用UTF-8编码的jstring,但是应用程序崩溃并且JNI写出错误:

I'm trying to return jstring encoded with UTF-8, but app crashes and JNI writes out error:

JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8: illegal continuation byte 0x30

我的代码段:

jstring Java_tgio_rncryptor_RNCryptorNative_generateKey(JNIEnv *env, jobject instance, const jstring salt_, const jstring password_)
 {
    const char *salt = env->GetStringUTFChars(salt_, 0);
    const char *password = env->GetStringUTFChars(password_, 0);
    RNCryptor *cryptor = new RNCryptor();
    string value = (char * )cryptor->generateKey(salt, password).data();
    delete cryptor;
    env->ReleaseStringUTFChars(salt_, salt);
    env->ReleaseStringUTFChars(password_, password);
    return env->NewStringUTF(value.c_str());
}

也尝试过:

const char *returning = env->GetStringUTFChars(env->NewStringUTF(value.c_str()), 0);
return env->NewStringUTF(returning);

有什么建议吗?

推荐答案

cryptor->generateKey返回SecByteBlock(字节序列).在强制转换为(char *)并构造std::string时很有意义,因为它们不仅处理文本,而jstring保留文本(来自UTF-16编码的Unicode字符集).

cryptor->generateKey returns SecByteBlock, a sequence of bytes. While casting to (char *) and constructing a std::string make sense because they do not deal only with text, jstring holds text (from the Unicode character set in the UTF-16 encoding).

您的代码尝试将非文本字节转换为Java字符串.如果确实要这样做,则必须使用字符集和编码,其值0-255的任何序列均有效. (CP437就是一个.)

You code tries to convert non-text bytes to a Java string. If you really want to do that you have to use a character set and encoding for which any sequence of values 0-255 are valid. (CP437 would be one.)

但是,相反,您可以将数据保留在更接近数据类型的数据类型中:返回Java byte[].然后在Java端,您可以将字节序列转换为

But instead, you could keep the data in a datatype closer to what it is: return a Java byte[]. Then on the Java side, you could convert the sequence of bytes in to Base 64, if you want to pass the key around as a string.

通常,密码算法对字节序列或块进行操作.处理文本的只是应用程序或包装函数.您将检查RNCryptor是否为您执行此操作,但对我而言看起来不是那样.

In general, cryptographic algorithms operate on byte sequences or blocks. It's only the application or wrapper functions that deal with text. You'll have check if RNCryptor does that for you but it doesn't look like that to me.

这篇关于无法在JNI中编码为UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆