我想以字符串格式存储加密数据。不幸的是,我不能做到这一点,我不明白为什么。
出于某种原因,这行代码如下:
const str = new TextEncoder().encode(buff1);
创建一个具有更多字节和不同字节的字符串,而不是之前在Arraybuffer中的字节。
此代码的最终结果是将这些内容记录到控制台:
ArrayBuffer { byteLength: 139 }
ArrayBuffer { byteLength: 262 }
这是一个问题,因为它们应该是相似的,但它们不是。我尝试了很多替代方案,但所有可能的方法都以同样的问题告终。如果有人能告诉我如何解决这个问题,我将不胜感激。
请注意,EncryptText函数的工作方式应该是这样的。我只是为那些想要在IDE中运行代码的人添加了它。
async function encryptText(plainText, iv, password): Promise<ArrayBuffer> {
const ptUtf8 = new TextEncoder().encode(plainText);
const pwUtf8 = new TextEncoder().encode(password);
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);
const alg = { name: 'AES-GCM', iv: iv };
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']);
return crypto.subtle.encrypt(alg, key, ptUtf8);
};
async function encrBuffToUtf8Test() {
const plainData = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, ' +
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
const password = 'infamous';
const randomValues = crypto.getRandomValues(new Uint8Array(12));
const encryptionResult1 = await this.encryptText(plainData, randomValues, password);
const buff1 = Buffer.from(encryptionResult1);
const str = new TextEncoder().encode(buff1);
const utf8buff = new TextDecoder('utf-8').decode(buff);
const encryptionResult2 = utf8buff.buffer;
const resTest = encryptionResult1 === encryptionResult2;
if (!resTest) {
console.log(encryptionResult1);
console.log(encryptionResult2);
}
}
发布于 2018-05-30 05:48:14
我想我几乎每天都会写这篇文章作为答案,但我还是要说一遍,you can't convert arbitrary binary data to a string使用标准字符编码。它根本不是这样工作的。
考虑使用base64或十六进制。
https://stackoverflow.com/questions/50593420
复制相似问题