我正在尝试使用新的WebCrypto API。 window.crypto.subtle.encrypt 函数将加密文本输出为ArrayBuffer - 但稍后我想将此输出发送到我的服务器,所以我需要它作为字符串。 但现在我面临着一些关于转换的疯狂问题:
console.log(encrypted); //ArrayBuffer { byteLength: 28 } (sample output from encryption function)
var encryptedAsUint8 = new Uint8Array(encrypted);
console.log(encryptedAsUint8); //Uint8Array [ 25, 235, 161, 121, 221, 61, 132, 15, 161, 17...
var decoded = new TextDecoder("utf-8").decode(encrypted);
console.log(decoded); //�y�=��ͨ˫~���@��UcQ�
var decoded64 = btoa(encodeURIComponent(decoded));
console.log(decoded64); //JTE5JUVGJUJGJUJEeSVFRiVCRiVCRCUzRCVFRiVCRiVCRCUwRiVFRiVCRiVCRCUxMSVDRCVBOCVDQiVBQn4lRUYlQkYlQkQlRUYlQkYlQkQlMDIlN0YlRUYlQkYlQkQlNDAlRUYlQkYlQkQlRUYlQkYlQkRVY1ElRUYlQkYlQkQ=
var encodedAgain = decodeURIComponent(atob(decoded64));
console.log(encodedAgain); //�y�=��ͨ˫~���@��UcQ�
console.log(decoded === encodedAgain); //true - AS YOU CAN SEE, UNTIL THIS POINT THE CONTENT SEEMS TO BE THE SAME - but now:
var backToUint8 = new Uint8Array(new TextEncoder("utf-8").encode(encodedAgain));
console.log(backToUint8 === encrypted); //false ???????
console.log(backToUint8); //Uint8Array [ 25, 239, 191, 189, 121, 239, 191, 189, 61, 239,... ---> WHY IS THE ARRAY NOW A DIFFERENT ONE?
提前感谢任何有用的建议!抱歉我的英语不好。