• 继承自: {stream.Transform}

    Decipher 类的实例用于解密数据。 该类可以通过以下两种方式之一使用:

    • 作为可读写的[流][stream],其中写入加密的数据以在可读侧生成未加密的数据。
    • 使用 [decipher.update()] 和 [decipher.final()] 方法生成未加密的数据。

    [crypto.createDecipher()] 或 [crypto.createDecipheriv()] 方法用于创建 Decipher 实例。 不能使用 new 关键字直接地创建 Decipher 对象。

    示例,使用 Decipher 对象作为流:

    1. const crypto = require('crypto');
    2. const algorithm = 'aes-192-cbc';
    3. const password = '用于生成密钥的密码';
    4. // 密钥长度取决于算法。
    5. // 在此示例中,对于 aes192,它是 24 个字节(192 位)。
    6. // 改为使用异步的 `crypto.scrypt()`。
    7. const key = crypto.scryptSync(password, '盐值', 24);
    8. // IV 通常与密文一起传递。
    9. const iv = Buffer.alloc(16, 0); // 初始化向量。
    10. const decipher = crypto.createDecipheriv(algorithm, key, iv);
    11. let decrypted = '';
    12. decipher.on('readable', () => {
    13. while (null !== (chunk = decipher.read())) {
    14. decrypted += chunk.toString('utf8');
    15. }
    16. });
    17. decipher.on('end', () => {
    18. console.log(decrypted);
    19. // 打印: 要加密的数据
    20. });
    21. // 使用相同的算法、密钥和 iv 进行加密。
    22. const encrypted =
    23. '9d47959b80d428936beef61216ef0b7653b5d23a670e082bd739f6cebcb6038f';
    24. decipher.write(encrypted, 'hex');
    25. decipher.end();

    示例,使用 Decipher 和管道流:

    1. const crypto = require('crypto');
    2. const fs = require('fs');
    3. const algorithm = 'aes-192-cbc';
    4. const password = '用于生成密钥的密码';
    5. // 改为使用异步的 `crypto.scrypt()`。
    6. const key = crypto.scryptSync(password, '盐值', 24);
    7. // IV 通常与密文一起传递。
    8. const iv = Buffer.alloc(16, 0); // 初始化向量。
    9. const decipher = crypto.createDecipheriv(algorithm, key, iv);
    10. const input = fs.createReadStream('要解密的数据.enc');
    11. const output = fs.createWriteStream('解密后的数据.js');
    12. input.pipe(decipher).pipe(output);

    示例,使用 [decipher.update()] 和 [decipher.final()] 方法:

    1. const crypto = require('crypto');
    2. const algorithm = 'aes-192-cbc';
    3. const password = '用于生成密钥的密码';
    4. // 改为使用异步的 `crypto.scrypt()`。
    5. const key = crypto.scryptSync(password, '盐值', 24);
    6. // IV 通常与密文一起传递。
    7. const iv = Buffer.alloc(16, 0); // 初始化向量。
    8. const decipher = crypto.createDecipheriv(algorithm, key, iv);
    9. // 使用相同的算法、密钥和 iv 进行加密。
    10. const encrypted =
    11. '9d47959b80d428936beef61216ef0b7653b5d23a670e082bd739f6cebcb6038f';
    12. let decrypted = decipher.update(encrypted, 'hex', 'utf8');
    13. decrypted += decipher.final('utf8');
    14. console.log(decrypted);
    15. // 打印: 要加密的数据