首页  >  文章  >  web前端  >  Node.js 中的 decipher.update() 方法

Node.js 中的 decipher.update() 方法

PHPz
PHPz转载
2023-08-25 08:13:161082浏览

Node.js 中的 decipher.update() 方法

decipher.update()用于根据给定的编码格式用接收到的数据更新解密。它是 crypto 模块中的 Decipher 类提供的内置方法之一。如果指定了输入编码,则数据参数是字符串,否则数据参数是缓冲区

语法

decipher.update(data, [inputEncoding], [outputEncoding])

参数

以上参数描述如下 -

  • data  – 它需要数据作为传递以更新解密内容的输入。

  • inputEncoding  - 它将输入编码作为参数。可能的输入值为十六进制、base64 等。

  • outputEncoding – 它将输出编码作为参数。该参数的输入类型是字符串。可能的输入值为十六进制、base64 等。

示例

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

node decipherUpdate.js

decipherUpdate.js

// Example to demonstrate the use of decipher.final() method

// Importing the crypto module
const crypto = require('crypto');

// Initialising the AES algorithm
const algorithm = 'aes-192-cbc';
// Initialising the password used for generating key
const password = '12345678123456789';

// Retrieving key for the decipher object
const key = crypto.scryptSync(password, 'old data', 24);

// Initializing the static iv
const iv = Buffer.alloc(16, 0);

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Initializing the decipher object to get decipher
const encrypted = '083bfe1b2f91677e5d00add115be2f1b2e362e190406f5c6b60e86969bf03bff';
// const encrypted2 = '8d11772fce59f08e7558db5bf17b3112';

let decryptedValue = decipher.update(encrypted, 'hex', 'utf8');
// let decryptedValue1 = decipher.update(encrypted1, 'hex', 'utf8');

decryptedValue += decipher.final('utf8');

// Printing the result...
console.log("Decrypted value -- " + decryptedValue);
// console.log("Base64 String:- " + base64Value)

输出

C:\homeode>> node decipherUpdate.js
Decrypted value -- Some new text data

示例

让我们再看一个示例。

// Example to demonstrate the use of decipher.final() method

// Importing the crypto module
const crypto = require('crypto');

// Initialising the AES algorithm
const algorithm = 'aes-192-cbc';
// Initialising the password used for generating key
const password = '12345678123456789';

// Retrieving key for the decipher object
crypto.scrypt(password, 'salt', 24,
   { N: 512 }, (err, key) => {
      if (err) throw err;

   // Initializing the static iv
   const iv = Buffer.alloc(16, 0);

   // Initializing the decipher with algo, key and iv
   const decipher = crypto.createDecipheriv(algorithm, key, iv);
   const encrypted = '91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074';

   //Getting the decrypted string value
   const decrypted = decipher.update(encrypted, 'hex', 'utf8');

   // Printing the result...
   console.log("Decrypted value:- " + decrypted);
});

输出

C:\homeode>> node decipherUpdate.js
Decrypted value:- Some new text data

以上是Node.js 中的 decipher.update() 方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除