首页 > 解决方案 > 使用 webcrypto API 的 AES_GCM 加密

问题描述

我遇到了一个 AES_GCM 实现,它的加密功能如下:

async function encryptMessage(key){
    let encodedMessage = encodeMessage();
    cipherText = await window.crypto.subtle.encrypt(
        {
            name: "AES-GCM",
            iv: window.crypto.getRandomValues(new Uint8Array(12))
        },
        key,
        encodedMessage
    );
    let buffer = new Uint8Array(cipherText, 0, 5);
    console.log(buffer);
    console.log(btoa(buffer));
}

我的问题是,为什么

新的 Uint8Array(cipherText, 0, 5);

有参数0和5。我在网上搜索,发现这些参数代表一个视图。但为什么只有 0 和 5?我们可以使用这些以外的数字吗?

标签: javascriptcryptographyaes-gcmwebcrypto-api

解决方案


我认为该示例来自https://github.com/mdn/dom-examples/blob/master/web-crypto/encrypt-decrypt/aes-gcm.js,这是 MDN 示例的一部分。

我的理解是他们只是向用户显示前几个字符,以证明它已被加密。您将看到真实内容保存在 中cipherText,其中还有iv一个模块级变量。


推荐阅读