Node.js 中的 crypto.createCipheriv() 方法
node.jsjavascriptweb developmentfront end technology
crypto.createCipheriv() 方法将首先根据给定密钥和授权因子 (iv) 传递的算法创建并返回密码对象。
语法
crypto.createCipheriv(algorithm, key, iv, options)
参数
上述参数描述如下 −
算法——它接受用于创建密码的算法的输入。一些可能的值是:aes192、aes256 等。
密钥——它接受算法使用的原始密钥和 iv 的输入。可能的值可以是以下类型:string、buffer、TypedArray 或 DataView。它可以是 secret 类型的类型对象。
iv ——也称为初始化向量。此参数接受 iv 的输入,这将使密码不确定且唯一。它不需要是 secret。其可能的值类型为:string、buffer、TypedArray、DataView。如果密码不需要,则可以为 null。
options ——这是用于控制流行为的可选参数。当密码在 CCM 或 OCB 模式下使用时,这不是可选的(如 'aes-256-ccm')
示例
创建一个名为 – createCipheriv.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −
node createCipheriv.js
createCipheriv.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 crypto = cipher.update(text); crypto = Buffer.concat([encrypted, cipher.final()]); // 返回 iv 和加密数据 return { iv: iv.toString('hex'), encryptedData: crypto.toString('hex') }; } // 打印公钥和私钥曲线密钥... var output = encrypt("TutorialsPoint"); console.log(output);
输出
C:\home
ode>> 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, 'TutorialsPoint', 24); // 初始化 iv 向量 const iv = Buffer.alloc(16, 0); // 使用上面定义的参数创建密码 const cipher = crypto.createCipheriv(algorithm, key, iv); let enabled = ''; // 读取和加密数据 cipher.on('readable', () => { let chunk; while (null !== (chunk = cipher.read())) { enabled += chunk.toString('base64'); } }); // 处理关闭/结束事件 cipher.on('end', () => { console.log(encrypted); }); // 打印公钥和私钥曲线密钥... cipher.write('TutorialsPoint'); cipher.end(); console.log("Completed... !");
输出
C:\home
ode>> node createCipheriv.js Completed... ! uqeQEkXy5dpJjQv+JDvMHw==