1

我的理解是,理论上,CTR 模式下的 AES 分组密码允许解密大文件的任何位置,而无需读取整个文件。

但是,我看不到如何使用 nodejs 加密模块执行此操作。我可以Decipher.update用虚拟块为方法提供数据,直到到达我感兴趣的部分,此时我将从文件中读取的实际数据提供给我,但这将是一个可怕的 hack、低效且脆弱,因为我需要注意块大小。

有没有办法用加密模块做到这一点,如果没有,我可以使用什么模块?

4

2 回答 2

1

我找到了不同的方法来解决这个问题:

方法一:点击率模式

这个答案基于@ArtjomB。和@gusto2 评论和回答,这真的给了我解决方案。但是,这是一个带有工作代码示例的新答案,它还显示了实现细节(例如,IV 必须作为大端数递增)。

这个想法很简单:要从块的偏移量开始解密n,只需将 IV 增加n. 每个块为 16 个字节。

import crypto = require('crypto');
let key = crypto.randomBytes(16);
let iv = crypto.randomBytes(16);

let message = 'Hello world! This is test message, designed to be encrypted and then decrypted';
let messageBytes = Buffer.from(message, 'utf8');
console.log('       clear text: ' + message);

let cipher = crypto.createCipheriv('aes-128-ctr', key, iv);
let cipherText = cipher.update(messageBytes);
cipherText = Buffer.concat([cipherText, cipher.final()]);

// this is the interesting part: we just increment the IV, as if it was a big 128bits unsigned integer. The IV is now valid for decrypting block n°2, which corresponds to byte offset 32
incrementIV(iv, 2); // set counter to 2

let decipher = crypto.createDecipheriv('aes-128-ctr', key, iv);
let decrypted = decipher.update(cipherText.slice(32)); // we slice the cipherText to start at byte 32
decrypted = Buffer.concat([decrypted, decipher.final()]);
let decryptedMessage = decrypted.toString('utf8');
console.log('decrypted message: ' + decryptedMessage);

该程序将打印:

       明文:世界你好!这是测试消息,旨在加密然后解密
解密消息:e,设计为先加密再解密

正如预期的那样,解密的消息移动了 32 个字节。

最后,这里是 incrementIV 的实现:

function incrementIV(iv: Buffer, increment: number) {
    if(iv.length !== 16) throw new Error('Only implemented for 16 bytes IV');

    const MAX_UINT32 = 0xFFFFFFFF;
    let incrementBig = ~~(increment / MAX_UINT32);
    let incrementLittle = (increment % MAX_UINT32) - incrementBig;

    // split the 128bits IV in 4 numbers, 32bits each
    let overflow = 0;
    for(let idx = 0; idx < 4; ++idx) {
        let num = iv.readUInt32BE(12 - idx*4);

        let inc = overflow;
        if(idx == 0) inc += incrementLittle;
        if(idx == 1) inc += incrementBig;

        num += inc;

        let numBig = ~~(num / MAX_UINT32);
        let numLittle = (num % MAX_UINT32) - numBig;
        overflow = numBig;

        iv.writeUInt32BE(numLittle, 12 - idx*4);
    }
}

方法2:CBC模式

由于 CBC 使用前一个密文块作为 IV,并且所有密文块在解密阶段都是已知的,因此您无需做任何特别的事情,您可以在流的任何点解密。唯一的问题是您解密的第一个块将是垃圾,但下一个块会很好。所以你只需要在你真正想要解密的部分之前开始一个块。

于 2018-04-21T20:33:30.343 回答
1

我可以为 Decipher.update 方法提供虚拟块,直到我到达我感兴趣的部分

正如@Artjom 已经评论的那样,假设使用 CTR 模式,您不需要提供文件的开头或任何虚拟块。您可以直接输入您感兴趣的密文。(使用 AES 启动 128 位的块大小)

查看CTR 操作模式,您只需将 IV 计数器设置为密文的起始块,只提供要解密的加密文件的一部分(如果需要,您可能需要提供起始块的虚拟字节)

例子:

您需要使用 AES 从位置 1048577 解密文件,它是块 65536 (1048577/16) 加上 1 个字节。所以你将IV设置为nonce|65536,解密虚拟1字节(移动到16 * 65536 + 1的位置)然后你可以从你感兴趣的文件部分提供你的密文

于 2018-04-21T17:01:18.830 回答