我的理解是,从理论上讲,CTR模式下的AES分组密码允许破译大文件的任何位置,而无需读取整个文件。
但是,我不知道如何使用nodejs加密模块执行此操作。我可以用虚拟块馈送Decipher.update
方法,直到我到达我感兴趣的部分,此时我会提供从文件中读取的实际数据,但这将是一个可怕的黑客,效率低下且脆弱,因为我需要知道块大小。
有没有办法使用加密模块做到这一点,如果没有,我可以使用什么模块?
我可以用虚拟块为 Decipher.update 方法提供,直到我到达我感兴趣的部分
正如@Artjom已经评论的那样,假设使用CTR模式,您不需要输入文件的开头或任何虚拟块。您可以直接提供您感兴趣的密文。(使用 AES 启动 128 位的块大小)
看到CTR的操作模式,你只需要将IV计数器设置为密文的起始块,只馈送部分要破译的加密文件(如果需要,可能需要馈送起始块的虚拟字节)
例:
您需要从位置 1048577 解密文件,使用 AES 它是块 65536 (1048577/16) 加 1 个字节。因此,您将IV设置为nonce|65536
,解密虚拟1字节(移动到16 * 65536 + 1的位置),然后您可以从您感兴趣的文件部分提供密文
我找到了解决这个问题的不同方法:
方法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 个字节。
最后,这是增量IV实现:
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,并且所有密文块在解密阶段都是已知的,因此您没有任何特别的事情要做,您可以在流的任何点解密。唯一的问题是,您解密的第一个块将是垃圾,但下一个块会很好。因此,您只需要在实际要解密的部分之前启动一个块。