该方法将首先根据为给定密钥和授权因子 (iv) 传递的算法创建并返回密码对象。crypto.createCipheriv()
crypto.createCipheriv(algorithm, key, iv, options)
上述参数描述如下 -
algorithm - 它需要用于创建密码的算法的输入。一些可能的值是:aes192、aes256 等。
key – 它接受算法和iv使用的原始密钥的输入。可能的值可以是以下类型:字符串、缓冲区、TypedArray 或 DataView。它可以选择是秘密类型的类型对象。
iv – 也称为初始化向量。此参数接受 iv 的输入,这将使密码不确定且唯一。它不需要是秘密。其可能的值类型有:字符串、缓冲区、TypedArray、DataView。如果密码不需要,这可以为空。
options - 这是用于控制流行为的可选参数。在 CCM 或 OCB 模式下使用密码时,这不是可选的(如“aes-256-ccm”)
创建一个具有名称的文件 -createCipheriv.js并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 -
node createCipheriv.js
创建Cipheriv.js
// 创建ECDH的节点演示程序 // 导入加密模块 const crypto = require('crypto'); // 初始化算法 const algorithm = 'aes-256-cbc'; // 初始化密钥 const key = crypto.randomBytes(32); // 初始化 iv 向量 const iv = crypto.randomBytes(16); // 创建加密数据的函数 function encrypt(text) { // 使用上面定义的参数创建密码 let cipher = crypto.createCipheriv( 'aes-256-cbc', Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); // 返回 iv 和加密数据 return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }; } // Printing public & private curve keys... var output = encrypt("nhooo"); console.log(output);输出结果
C:\home\node>> node createCipheriv.js { iv: '3dd899aa441c00d4d8d2ff95abb2e684', encryptedData: 'b4985053bc1507fc25a4d99823dc8b03' }
让我们再看一个例子。
// 创建ECDH的节点演示程序 // 导入加密模块 const crypto = require('crypto'); // 初始化算法 const algorithm = 'aes-192-cbc'; // 定义和初始化密码 const password = '123456789' // 初始化密钥 const key = crypto.scryptSync(password, 'nhooo', 24); // 初始化 iv 向量 const iv = Buffer.alloc(16, 0); // 使用上面定义的参数创建密码 const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = ''; // 读取和加密数据 cipher.on('readable', () => { let chunk; while (null !== (chunk = cipher.read())) { encrypted += chunk.toString('base64'); } }); //处理关闭/结束事件 cipher.on('end', () => { console.log(encrypted); }); // Printing public & private curve keys... cipher.write('nhooo'); cipher.end(); console.log("完全的... !");输出结果
C:\home\node>> node createCipheriv.js 完全的... ! uqeQEkXy5dpJjQv+JDvMHw==