• 继承自: {stream.Transform}

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

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

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

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

    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. // 使用 `crypto.randomBytes()` 生成随机的 iv 而不是此处显示的静态的 iv。
    9. const iv = Buffer.alloc(16, 0); // 初始化向量。
    10. const cipher = crypto.createCipheriv(algorithm, key, iv);
    11. let encrypted = '';
    12. cipher.on('readable', () => {
    13. let chunk;
    14. while (null !== (chunk = cipher.read())) {
    15. encrypted += chunk.toString('hex');
    16. }
    17. });
    18. cipher.on('end', () => {
    19. console.log(encrypted);
    20. // 打印: 9d47959b80d428936beef61216ef0b7653b5d23a670e082bd739f6cebcb6038f
    21. });
    22. cipher.write('要加密的数据');
    23. cipher.end();

    示例,使用 Cipher 和管道流:

    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. // 使用 `crypto.randomBytes()` 生成随机的 iv 而不是此处显示的静态的 iv。
    8. const iv = Buffer.alloc(16, 0); // 初始化向量。
    9. const cipher = crypto.createCipheriv(algorithm, key, iv);
    10. const input = fs.createReadStream('要加密的数据.txt');
    11. const output = fs.createWriteStream('加密后的数据.enc');
    12. input.pipe(cipher).pipe(output);

    示例,使用 [cipher.update()] 和 [cipher.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. // 使用 `crypto.randomBytes()` 生成随机的 iv 而不是此处显示的静态的 iv。
    7. const iv = Buffer.alloc(16, 0); // 初始化向量。
    8. const cipher = crypto.createCipheriv(algorithm, key, iv);
    9. let encrypted = cipher.update('要加密的数据', 'utf8', 'hex');
    10. encrypted += cipher.final('hex');
    11. console.log(encrypted);
    12. // 打印: 9d47959b80d428936beef61216ef0b7653b5d23a670e082bd739f6cebcb6038f