Node.js 中的 crypto.createDecipheriv() 方法

node.jsjavascriptweb developmentfront end technology

crypto.createCipheriv() 是来自 'crypto' 模块的编程接口。它将根据给定的算法、密钥、iv 和传入函数的选项创建并返回 Decipher 对象。

语法

crypto.createDecipheriv(algorithm, key, iv, [options])

参数

上述参数描述如下 −

  • 算法 – 它接受用于创建密码的算法的输入。一些可能的值是:aes192、aes256 等。

  • key – 它接受算法和 iv 使用的原始密钥的输入。可能的值可以是以下类型:string、buffer、TypedArray 或 DataView。它可以是 secret 类型的类型对象。

  • iv  – 也称为初始化向量。此参数接受 iv 的输入,这将使密码不确定且唯一。它不需要是 secret。其可能的值类型为:string、buffer、TypedArray、DataView。如果密码不需要,则可以为 null。

  • options  – 这是用于控制流行为的可选参数。当密码在 CCM 或 OCB 模式下使用时,这不是可选的(如 'aes-256-ccm')

示例

创建一个名为 – createDecipheriv.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −

node createDecipheriv.js

createDecipheriv.js

// 用于创建 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 decipher = crypto.createDecipheriv(algorithm, key, iv);

let decrypted = '';

// 读取和加密数据
decipher.on('readable', () => {
   let chunk;
   while (null !== (chunk = decipher.read())) {
      decrypted += chunk.toString('utf8');
   }
});

//处理关闭/结束事件
decipher.on('end', () => {
   console.log(decrypted);
});

// 即将解密的加密数据
const crypto = 'uqeQEkXy5dpJjQv+JDvMHw==';
// 打印解密后的文本
decipher.write(encrypted, 'base64');
decipher.end();
console.log("Completed... !");

输出

C:\home
ode>> node createDecipheriv.js Completed... ! TutorialsPoint

示例

我们再看一个例子。

// 用于创建 ECDH 的节点演示程序

// 导入加密模块
const crypto = require('crypto');

// 初始化算法
const algorithm = 'aes-256-cbc';

// 定义和初始化密码
const password = '123456789'

// 初始化密钥
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);

// 使用连接
encrypted = Buffer.concat([encrypted, cipher.final()]);

// 返回 iv 向量以及加密数据
return { iv: iv.toString('hex'),
   encryptedData: crypto.toString('hex') };
}

//解密数据的解密函数
function decrypt(text) {

let iv = Buffer.from(text.iv, 'hex');
let cryptoText =
   Buffer.from(text.encryptedData, 'hex');

// 从算法、密钥和 iv 创建解密
let decipher = crypto.createDecipheriv(
   'aes-256-cbc', Buffer.from(key), iv);

// 更新解密文本
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);

// 解密后返回响应数据
return decrypted.toString();
}
// 加密以下数据并打印输出
var output = encrypt("Welcome to TutorialsPoint !");
console.log("Encrypted data -- ", output);

//打印解密数据
console.log("Decrypted data -- ", decrypt(output));

输出

C:\home
ode>> node createDecipheriv.js Encrypted data -- { iv: '3fb2c84290e04d9bfb099bc65a7ac941', encryptedData: '4490777e90c5a78037cb92a99d561ae250562e2636af459b911cfa01c0191e3f' } Decrypted data -- Welcome to TutorialsPoint !

相关文章