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


cipher.update() 用於根據給定的編碼格式更新已接收加密資料。它是由 crypto 模組中的 Cipher 類提供的一個內建方法。如果指定了一個輸入編碼,那麼資料引數是一個字串,否則資料引數是一個緩衝區

語法

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

引數

以上引數描述如下 −

  • data – 它將資料作為一個輸入,該資料傳遞給更新加密內容。

  • inputEncoding – 它將輸入編碼作為一個引數。可能的輸入值是十六進位制、base64 等。

  • outputEncoding – 它將輸出編碼作為一個引數。該引數的輸入型別是一個字串。可能的輸入值是十六進位制、base64 等。

示例

建立一個名為 cipherUpdate.js 的檔案,並複製下面的程式碼段。建立檔案後,使用以下命令執行此程式碼,如下例所示 −

node cipherUpdate.js

cipherUpdate.js

// Example to demonstrate the use of cipher.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 cipher object
const key = crypto.scryptSync(password, 'old data', 24);

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

// Initializing the cipher object to get cipher
const cipher = crypto.createCipheriv(algorithm, key, iv);

//Getting the updated string value with new data
let updatedValue = cipher.update('Welcome to tutorials point', 'utf8', 'hex');

//Adding the old value and updated value
updatedValue += cipher.final('hex');

// Printing the result...
console.log("Updated String:- " + updatedValue);

輸出

C:\home
ode>> node cipherUpdate.js Updated String:- a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a

示例

我們再看一個例子。

// Example to demonstrate the use of cipher.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 cipher 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 cipher object to get cipher
   const cipher = crypto.createCipheriv(algorithm, key, iv);

   //Getting the updated string value with new data
   let updatedValue = cipher.update('Some new text data', 'utf8', 'hex');
   //Adding the old value and updated value
   updatedValue += cipher.final('hex');

   // Printing the result...
   console.log("Updated String:- " + updatedValue);
});

輸出

C:\home
ode>> node cipherUpdate.js Updated String:- 91d6d37e70fbae537715f0a921d15152194435b96ce3973d92fbbc4a82071074

更新於: 2021-05-20

555 次瀏覽

開啟您的 職業生涯

透過完成課程來獲得認證

開始學習
廣告
© . All rights reserved.