2

我遇到的问题是,我得到的 JS-Objects 的字段如下......

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

    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”“45AB28” =K9 ¹j¶»¶ HH®¾¨Í¯®¾ÑêÕçã"

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

4

1 回答 1

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

这些脚本基于crypto.js

笔记:

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

资源:

于 2015-11-20T17:16:57.230 回答