Node.js 中的 crypto.createCipheriv() 方法
crypto.createCipheriv() 方法首先根据给定的密钥和授权因子 (iv) 创建并返回密码对象。
语法
crypto.createCipheriv(algorithm, key, iv, options)
参数
以上参数描述如下:
algorithm – 它接收用于创建密码的算法的输入。一些可能的值是:aes192、aes256 等。
key – 它接收算法和 iv 使用的原始密钥的输入。可能的值可以是:字符串、缓冲区、TypedArray 或 DataView 类型。它可以选择是 secret 类型的对象。
iv – 也称为初始化向量。此参数接收 iv 的输入,这将使密码不确定且唯一。它不需要保密。其可能的值类型为:字符串、缓冲区、TypedArray、DataView。如果密码不需要,则可以为 null。
options – 这是一个可选参数,用于控制流行为。当密码在 CCM 或 OCB 模式下使用时(例如 'aes-256-ccm'),此参数不是可选的。
示例
创建一个名为 createCipheriv.js 的文件并复制下面的代码片段。创建文件后,使用以下命令运行此代码,如下例所示:
node createCipheriv.js
createCipheriv.js
// A node demo program for creating the ECDH
// Importing the crypto module
const crypto = require('crypto');
// Initializing the algorithm
const algorithm = 'aes-256-cbc';
// Initializing the key
const key = crypto.randomBytes(32);
// Initializing the iv vector
const iv = crypto.randomBytes(16);
// Creating the function to encrypt data
function encrypt(text) {
// Creating the cipher with the above defined parameters
let cipher = crypto.createCipheriv(
'aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
// Returning iv and the encrypted data
return { iv: iv.toString('hex'),
encryptedData: encrypted.toString('hex') };
}
// Printing public & private curve keys...
var output = encrypt("TutorialsPoint");
console.log(output);输出
C:\home
ode>> node createCipheriv.js { iv: '3dd899aa441c00d4d8d2ff95abb2e684', encryptedData: 'b4985053bc1507fc25a4d99823dc8b03' }
示例
让我们再看一个例子。
// A node demo program for creating the ECDH
// Importing the crypto module
const crypto = require('crypto');
// Initializing the algorithm
const algorithm = 'aes-192-cbc';
// Defining and initializing the password
const password = '123456789'
// Initializing the key
const key = crypto.scryptSync(password, 'TutorialsPoint', 24);
// Initializing the iv vector
const iv = Buffer.alloc(16, 0);
// Creating the cipher with the above defined parameters
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = '';
// Reading and encrypting the data
cipher.on('readable', () => {
let chunk;
while (null !== (chunk = cipher.read())) {
encrypted += chunk.toString('base64');
}
});
//Handling the closing/end event
cipher.on('end', () => {
console.log(encrypted);
});
// Printing public & private curve keys...
cipher.write('TutorialsPoint');
cipher.end();
console.log("Completed... !");输出
C:\home
ode>> node createCipheriv.js Completed... ! uqeQEkXy5dpJjQv+JDvMHw==
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP