简体   繁体   中英

encrypt and decrypt utf8 string in android NDK jni

i write a simple string encrypt and decrypt with split string to two var and increment assci code and after swap right and left of string.

when i encrypt this text = "this is test" this is work well, but when encrypt utf char don't word like this string = "تست تست تست تست"

encrypt code is :

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);
}

and decrypt code is :

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 function :

char* substr(const char *source, unsigned int start, unsigned int end) {
return strndup(source + start, end);
}

Does anyone have solution .

UTF-8 is not trivial for manipulations. For your encode/decode, you can use GetStringChars() (or the more efficient, but also more restrictive GetStringCritical() ) and operate the resulting 16-bit jchar array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM