我写一个简单的字符串加密和解密,用拆分字符串到两个var和increment assci代码,然后在字符串的左右交换。
当我加密这个文本=“这是测试”时这很好用,但是当加密时,utf char不会像这样的字符串=“تستتتتتتتتتتتتتت”
加密代码是:
JNIEXPORT jstring JNICALL Java_com_test_ndk_MainActivity_encrypt(JNIEnv* env, jobject thiz, jstring dec) {
const char *nativeString = (*env)->GetStringUTFChars(env, dec, 0);
char *newstr;
char *left;
char *right;
int decLenght = strlen(nativeString);
int middl = decLenght / 2;
int i;
newstr = substr(nativeString, 0, middl);
int lenght = strlen(newstr);
left = malloc(lenght);
for (i = 0; i < lenght; i++) {
left[i] = newstr[i] + 1;
}
left[lenght] = '\0';
newstr = substr(nativeString, middl, decLenght - middl);
lenght = strlen(newstr);
right = malloc(lenght);
for (i = 0; i < lenght; i++) {
right[i] = newstr[i] - 1;
}
right[lenght] = '\0';
strcat(right, left);
(*env)->ReleaseStringUTFChars(env, dec, nativeString);
return (*env)->NewStringUTF(env, right);
}
和解密代码是:
JNIEXPORT jstring JNICALL Java_com_test_ndk_MainActivity_decrypt(JNIEnv* env, jobject thiz, jstring enc) {
const char *nativeString = (*env)->GetStringUTFChars(env, enc, 0);
char *newstr;
char *left;
char *right;
int encLenght = strlen(nativeString);
int middl = encLenght / 2;
int i;
if (encLenght % 2 != 0) {
middl++;
}
newstr = substr(nativeString, 0, middl);
int lenght = strlen(newstr);
left = malloc(lenght);
for (i = 0; i < lenght; i++) {
left[i] = (char) ((int) newstr[i] + 1);
}
left[lenght] = '\0';
newstr = substr(nativeString, middl, encLenght - middl);
lenght = strlen(newstr);
right = malloc(lenght);
for (i = 0; i < lenght; i++) {
right[i] = (char) ((int) newstr[i] - 1);
}
right[lenght] = '\0';
strcat(right, left);
(*env)->ReleaseStringUTFChars(env, enc, nativeString);
return (*env)->NewStringUTF(env, right);
}
substr函数:
char* substr(const char *source, unsigned int start, unsigned int end) {
return strndup(source + start, end);
}
有没有人有解决方案。
答案 0 :(得分:0)
UTF-8对于操作并非易事。对于您的编码/解码,您可以使用GetStringChars()
(或更有效但限制性更强的GetStringCritical()
)并运行生成的16位 jchar 数组。