我正在尝试使用AES-CTR算法在浏览器上解密数据。WebCrypto API要求将计数器作为BufferSource传递。如何将计数器(一个数字)转换为期望的输入(一个字节数组)?
我使用的是全零IV,所以计数器从0开始。假设我正在尝试解密计数器为445566的数据。如何将445566转换为ArrayBuffer?
我使用的是全零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)
编辑:在查找一些加密库后,我最终使用了这个。它似乎可以做到我想要的,但对于正确性、性能等方面没有任何想法。
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
}
const iv = Buffer.alloc(16)
。如果密钥仅用于加密单个消息,则可以使用全零IV。 - Eric Guan