1

我需要在浏览器中解密用 AES-CTR 256 位编码的消息(使用 OpenSSL 编码)。

使用 OpenSSL 我得到类似的东西:

key=189BBBB00C5F1FB7FBA9AD9285F193D1771D7611CB891E5C1F4E24C20E50FB1D
iv =4103C88663AE12CE18EA46E894280C4D
msg=nhVKeu8zNO2PRTwJrDE=

好吧,我的问题是将这些字符串转换为window.crypto.subtleAPI 可以管理的对象。例如。

const counter = ???;
const ciphertext = ???;
const rawKey = ???;

const key = window.crypto.subtle.importKey(
    "raw",
    key,
    "AES-CTR",
    true,
    ["encrypt", "decrypt"]
);

const decrypted = await window.crypto.subtle.decrypt(
{
    name: "AES-CTR",
    counter,
    length: 64
  },
  key,
  ciphertext
);

let dec = new TextDecoder();
const msg = dec.decode(decrypted);
console.log(msg);

谁能帮我从key, iv,msgcounter, ciphertext, rawkey?

非常感谢

4

1 回答 1

1

密钥、计数器(或 IV)和密文可以作为 传递TypedArray,即您需要两次转换,一次从十六进制转换,第二次从 Base64 编码字符串转换为TypedArray,例如

从十六进制编码的字符串,这里

const fromHex = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));

来自 Base64 编码的字符串,这里

const fromBase64 = base64String => Uint8Array.from(atob(base64String), c => c.charCodeAt(0));

在代码本身await中缺少一个运算符,并且必须在importKey函数中使用而不是(可能是复制/粘贴错误)。全部一起:rawKeykey

const fromHex = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
const fromBase64 = base64String => Uint8Array.from(atob(base64String), c => c.charCodeAt(0));
		
async function test(){
		
    const rawKey = fromHex("189BBBB00C5F1FB7FBA9AD9285F193D1771D7611CB891E5C1F4E24C20E50FB1D");
    const counter = fromHex("4103C88663AE12CE18EA46E894280C4D");
    const ciphertext = fromBase64("nhVKeu8zNO2PRTwJrDE=");

    const key = await window.crypto.subtle.importKey(   // add >await<
        "raw",
        rawKey,                                         // replace >key< with >rawKey<
        "AES-CTR",
        true,
        ["encrypt", "decrypt"]
    );

    const decrypted = await window.crypto.subtle.decrypt(
        {
            name: "AES-CTR",
            counter,
            length: 64
        },
        key,
        ciphertext
    );

    let dec = new TextDecoder();
    const msg = dec.decode(decrypted);
    console.log(msg);
}

test();

这将密文解密为:

hello, world!
于 2020-04-02T20:04:21.123 回答