OpenHarmony应用开发-加解密中文乱码问题FAQ
·
FAQ
加解密中文字符串时乱码
在OpenHarmony应用开发加解密功能时,经常会遇到加解密中文字符串乱码的问题。经采样分析,该问题的根因不在于加解密算法或者公私钥的问题导致,而是加解密前后string与Uint8Array的转换没有考虑到中文字符位数导致。因此,可以参考下述方案:
// 字符串转成字节流
function stringToUint8Array(str: string) {
return new Uint8Array(buffer.from(str, 'utf-8').buffer);
}
// 字节流转成字符串
function uint8ArrayToString(array: Uint8Array) {
// 将UTF-8编码转换成Unicode编码
let out: string = '';
let index: number = 0;
let len: number = array.length;
while (index < len) {
let character = array[index++];
switch(character >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
out += String.fromCharCode(character);
break;
case 12:
case 13:
out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F));
break;
case 14:
out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | ((array[index++] & 0x3F) << 0));
break;
default:
break;
}
}
return out;
}
相关文献
https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/crypto-rsa-asym-encrypt-decrypt-pkcs1
更多推荐
所有评论(0)