网站搜索

javascript - 转换为 UInt8 时,表情符号和“дей”等字符将导致错误


我有一个问题:我收到的 JS 对象包含诸如...标题:“действительный有效なដែលមាន...”之类的字段,或者例如包含此表情符号😍。现在,由于加密,我需要将这些信息转换为 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”:“действительный有效なដែលមានសុពលភាព有效有效માન્યમાבתוקף”,以及将其格式化回后的输出字符串,例如:“title”:“459AB28B5;L=K9 ``j¶¶¶ H H®ϑêÍй®ϑêÕçã”

你知道为什么会发生这种情况吗?谢谢!

答案#1

以下脚本加密和解密 dataToEncrypt。它使用现代编码 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;
}
  • 前一个脚本的 jsFiddle
  • 没有编码 API 版本的 jsFiddle

这些脚本基于 crypto.js。

注意:

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

资源:

  • https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder/encode
  • https://googlechrome.github.io/samples/encoding-api/index.html
  • https://developer.mozilla.org/zh-CN/docs/Web/API/SubtleCrypto/encrypt