Node.js 中的 cipher.update() 方法
node.jsjavascriptweb developmentfront end technology
cipher.update() 用于根据给定的编码格式使用接收的数据更新密码。它是 crypto 模块中的 Cipher 类提供的内置方法之一。如果指定了输入编码,则数据参数是字符串,否则数据参数是缓冲区
语法
cipher.update(data, [inputEncoding], [outputEncoding])
参数
上述参数描述如下 −
data –它将数据作为输入,并传递该输入来更新密码内容。
inputEncoding – 它将输入编码作为参数。可能的输入值为 hex、base64 等。
outputEncoding – 它将输出编码作为参数。此参数的输入类型为字符串。可能的输入值为 hex、base64 等。
示例
创建一个名为 – cipherUpdate.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −
node cipherUpdate.js
cipherUpdate.js
// 示例演示如何使用 cipher.final() 方法 // 导入 crypto 模块 const crypto = require('crypto'); // 初始化 AES 算法 const algorithm = 'aes-192-cbc'; // 初始化用于生成密钥的密码 const password = '12345678123456789'; // 检索密码对象的密钥 const key = crypto.scryptSync(password, 'old data', 24); // 初始化静态 iv const iv = Buffer.alloc(16, 0); // 初始化密码对象以获取密码 const cipher = crypto.createCipheriv(algorithm, key, iv); //使用新数据获取更新的字符串值 let updatedValue = cipher.update('Welcome to tutorials point', 'utf8', 'hex'); //添加旧值和更新值 updatedValue += cipher.final('hex'); // 打印结果... console.log("Updated String:- " + updatedValue);
输出
C:\home
ode>> node cipherUpdate.js Updated String:- a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a
示例
我们再看一个例子。
// 示例演示如何使用 cipher.final() 方法 // 导入 crypto 模块 const crypto = require('crypto'); // 初始化 AES 算法 const algorithm = 'aes-192-cbc'; // 初始化用于生成密钥的密码 const password = '12345678123456789'; // 检索密码对象的密钥 crypto.scrypt(password, 'salt', 24, { N: 512 }, (err, key) => { if (err) throw err; // 初始化静态 iv const iv = Buffer.alloc(16, 0); // 初始化密码对象以获取密码 const cipher = crypto.createCipheriv(algorithm, key, iv); //使用新数据获取更新的字符串值 let updatedValue = cipher.update('一些新的文本数据', 'utf8', 'hex'); //添加旧值和更新值 updatedValue += cipher.final('hex'); //打印结果... console.log("Updated String:- " + updatedValue); });
输出
C:\home
ode>> node cipherUpdate.js Updated String:- 91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074