将数字转换为 ArrayBuffer

Eri*_*uan 7 javascript cryptography aes webcrypto-api

我正在尝试使用 AES-CTR 算法解密浏览器上的数据。WebCrypto API要求将计数器作为BufferSource传递。如何将计数器(数字)转换为预期输入(字节数组)?

我使用的是全零 IV,因此计数器从 0 开始。假设我正在尝试解密计数器 = 445566 的数据。如何将 445566 转换为 ArrayBuffer?

const key = // retrieve decryption key
const encrypted = // retrieve encrypted data

const iv = new ArrayBuffer(16)
// iv is all zeros. I need it to represent 445566, how?

const algo = {
    name: 'AES-CTR',
    counter: iv,
    length: 128
}
const decrypted = await crypto.subtle.decrypt(algo, key, encrypted)
Run Code Online (Sandbox Code Playgroud)

编辑:在挖掘了一些加密库之后,我最终使用了这个。它似乎做了我想做的事,但不知道正确性、性能等。

function numberToArrayBuffer(value) {
    const view = new DataView(new ArrayBuffer(16))
    for (var index = 15; index >= 0; --index) {
      view.setUint8(index, value % 256)
      value = value >> 8;
    }
    return view.buffer
}
Run Code Online (Sandbox Code Playgroud)

Bur*_*tlı 11

有一个针对 IE10+ 的单行解决方案:)

new Int32Array([n]).buffer
Run Code Online (Sandbox Code Playgroud)


kar*_*ick 1

不确定这是否有帮助。但只是为了交叉检查代码的真实性。

我编写了一些测试用例,首先将数字转换为数组缓冲区,然后使用数组缓冲区值将其解码为相同的值。

var hex = 445566..toString(16);
var buffer = new ArrayBuffer(16);
var dataView = new DataView(buffer);
dataView.setInt32(0, '0x'+ hex);
console.log(dataView.getInt32(0)); //445566


//Using the uint16array data generated by the above code 
var data = [0, 6, 204, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var buf = new ArrayBuffer(16);
var view = new DataView(buf);
data.forEach(function (b, i) {
    view.setUint8(i, b % 256);
});
var num = view.getInt32(0);
console.log(num);//445566


function numberToArrayBuffer(value) {
    const view = new DataView(new ArrayBuffer(16))
    for (var index = 15; index >= 0; --index) {
      view.setUint8(index, value % 256)
      value = value >> 8;
    }
    return view.buffer
}

console.log(numberToArrayBuffer(445566)) //  Uint8Array(16) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 204, 126]
Run Code Online (Sandbox Code Playgroud)

两者的结果是一样的。只是您的代码以大端格式生成结果,而我的代码以小端格式生成结果。

所以你遵循的方法是正确的。至于性能我认为影响不大