表情符号和字符如 дей 在 UInt8 转换时被破坏

Emoticons and chars like дей are broken while UInt8 conversion

我遇到的问题是 JS-Objects 字段如下...将此信息转换为 UInt8。

处理转换的代码如下所示(并且在一般情况下可以正常工作...)

    public arrayBufferToString(arrayBuffer : Uint8Array) : string {
        var str : string = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
        return str;
    }

    public stringToArrayBuffer(string:string) : Uint8Array {
        if(typeof string === 'undefined' || string === null){
            this.$log.warn('Cannot convert an undefined string');
            return null;
        }

        var arrayBuffer : any = new ArrayBuffer(string.length);
        var buffer : Uint8Array = new Uint8Array(arrayBuffer);
        for (var i : number = 0, stringLength : number = string.length; i < stringLength; i++) {
            buffer[i] = string.charCodeAt(i);
        }
        return buffer;
    }

然而,在这些情况下,我有这样的输入: "title":"действительный有效率naដែលមានសុពលភាព有效率માન્યમાבתוקף"和输出,在将其格式化回字符串后,像这样 "title":"459AB28B5;L=K9 ¹j¶»¶ H H®¾¨Í¯®¾ÑêÕçã"

你知道为什么会这样吗?谢谢!

以下脚本加密和解密 dataToEncrypt。它使用现代 Encoding API.

"use strict";

var dataToEncrypt = "дей ... hopefully, it means 'day' :)";
var iv = window.crypto.getRandomValues(new Uint8Array(16));
var algorithm = {
    name: "AES-CBC",
    iv: iv
};

window.crypto.subtle.generateKey(
    {
        name: "AES-CBC",
        length: 128
    },
    /* extractable */ true,
    /*keyUsages */ ['encrypt', 'decrypt']
).
then(function (aesKey) {
        var uint16array = new TextEncoder('utf-16').encode(dataToEncrypt);

        window.crypto.subtle.encrypt(algorithm, aesKey, uint16array)
            .then(function (encryptedArrayBuffer) {

                console.log("encrypted", ab2hexstr(encryptedArrayBuffer));

                window.crypto.subtle.decrypt(algorithm, aesKey, encryptedArrayBuffer)
                    .then(function (result) {
                        console.log("decrypted", new TextDecoder('utf-16').decode(result));
                    })
                    .catch(function (err) {
                        console.log("Decryption failed.", err);
                    });
            })
            .catch(function (err) {
                console.log("Encryption failed.", err);
            });
    }
).
catch(function (err) {
    console.log("generateKey - failed.", err);
});

function ab2hexstr(buf) {
    var byteArray = new Uint8Array(buf);
    var hexString = "";
    var nextHexByte;

    for (var i = 0; i < byteArray.byteLength; i++) {
        nextHexByte = byteArray[i].toString(16);  // Integer to base 16
        if (nextHexByte.length < 2) {
            nextHexByte = "0" + nextHexByte;     // Otherwise 10 becomes just a instead of 0a
        }
        hexString += nextHexByte;
    }
    return hexString;
}

脚本基于crypto.js

注:

我没有使用 TypeScript,但您可以根据需要添加类型。

资源: