首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将加密数据转换为字符串,然后再转换回来

将加密数据转换为字符串,然后再转换回来
EN

Stack Overflow用户
提问于 2018-05-30 05:45:37
回答 1查看 154关注 0票数 0

我想以字符串格式存储加密数据。不幸的是,我不能做到这一点,我不明白为什么。

出于某种原因,这行代码如下:

代码语言:javascript
复制
const str = new TextEncoder().encode(buff1); 

创建一个具有更多字节和不同字节的字符串,而不是之前在Arraybuffer中的字节。

此代码的最终结果是将这些内容记录到控制台:

ArrayBuffer { byteLength: 139 }

ArrayBuffer { byteLength: 262 }

这是一个问题,因为它们应该是相似的,但它们不是。我尝试了很多替代方案,但所有可能的方法都以同样的问题告终。如果有人能告诉我如何解决这个问题,我将不胜感激。

请注意,EncryptText函数的工作方式应该是这样的。我只是为那些想要在IDE中运行代码的人添加了它。

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-30 05:48:14

我想我几乎每天都会写这篇文章作为答案,但我还是要说一遍,you can't convert arbitrary binary data to a string使用标准字符编码。它根本不是这样工作的。

考虑使用base64或十六进制。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50593420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档