使用 NodeJS(带 Typescript)流和 aes-gcm 算法时,不支持的状态或无法验证数据错误



尝试通过密码/解密流加密和解密文件时,我总是遇到以下错误:Unsupported state or unable to authenticate data

这是代码(流和非流版本之间的比较(:

非流版本

const key = Buffer.alloc(256 / 8);
const text = 'my secret message';
const encrypter = crypto.createCipheriv('aes-256-gcm', key, Buffer.alloc(16));
let encrypted = encrypter.update(text, 'utf8', 'hex');
encrypted += encrypter.final('hex');
const tag = encrypter.getAuthTag();
console.log('Encrypted!', encrypted);
const decrypter = crypto.createDecipheriv('aes-256-gcm', key, Buffer.alloc(16));
decrypter.setAuthTag(tag);
let decrypted = decrypter.update(encrypted, 'hex', 'utf8');
decrypted += decrypter.final('utf8');
console.log('Decrypted', decrypted);

这完美地打印出Decrypted my secret message另一方面...

流版本

const key = Buffer.alloc(256 / 8);
const text = 'my secret message';
const cipher = crypto.createCipheriv('aes-256-gcm', key, Buffer.alloc(16));
let encrypted = '';
cipher.on('data', (data: Buffer) => 
{
    encrypted += data.toString('hex');
});
cipher.on('end', () => 
{
    const tag = cipher.getAuthTag();
    const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.alloc(16));
    decipher.setAuthTag(tag);
    let decrypted = '';
    decipher.on('readable', () => 
    {
        const data = decipher.read() as Buffer;
        if(data)
            decrypted += data.toString('utf8');
    });
    decipher.on('end', () => 
    {
        console.log(decrypted);
    });
    fromString(encrypted).pipe(decipher);
});

我假设实用程序函数fromString从 from2 包的示例中挑选

import * as from from 'from2';
function fromString(text: string) 
{
    return from((size, next) => 
    {
        if (text.length <= 0) 
            return next(null, null);
        const chunk = text.slice(0, size);
        text = text.slice(size);
        next(null, chunk);
    });
}

关于为什么这不能正常工作的任何提示?谢谢。我很坚持这一点。

实际上,以下代码在文件上运行良好。我不知道这个和我发布的那个有什么区别......

const algorithm = 'aes-256-gcm';
const iv = Buffer.alloc(16);
const key = Buffer.alloc(256/8);
const cipher = crypto.createCipheriv(algorithm, key, iv);
const read_stream = fs.createReadStream(path.resolve(os.homedir(), 'Desktop', 'abstract.pdf'));
const encrypted_write_stream = fs.createWriteStream(path.resolve(os.homedir(), 'Desktop', 'abstract.enc.pdf'));
cipher.on('finish', () => 
{
    const tag = cipher.getAuthTag();
    console.log('File encrypted. Tag is', tag.toString('hex'));
    const decipher = crypto.createDecipheriv(algorithm, key, iv);
    decipher.setAuthTag(tag);
    const encrypted_read_stream = fs.createReadStream(path.resolve(os.homedir(), 'Desktop', 'abstract.enc.pdf'));
    const write_stream = fs.createWriteStream(path.resolve(os.homedir(), 'Desktop', 'abstract.decrypted.pdf'));
    decipher.on('error', console.error);
    decipher.on('finish', () => 
    {
        console.log('Decrypted successfully');
    });
    encrypted_read_stream.pipe(decipher).pipe(write_stream);
});
read_stream.pipe(cipher).pipe(encrypted_write_stream);

相关内容

最新更新