當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js cipher.update()用法及代碼示例

cipher.update()方法是加密模塊內的Cipher類的內置應用程序編程接口,用於根據給定的編碼格式用數據更新密碼。

用法:

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

參數:此方法采用以下參數:

  • data:它用於通過新內容更新密碼。
  • inputEncoding:輸入編碼格式。
  • outputEncoding:輸出編碼格式。

返回值:此方法返回包含密碼值的緩衝區的對象。

範例1: 文件名:index.js



Javascript

// Node.js program to demonstrate the 
// cipher.update() method 
  
// Importing crypto module 
const crypto = require('crypto'); 
  
// Creating and initializng algorith and password 
const algorithm = 'aes-192-cbc'; 
const password = 'Password used to generate key'; 
  
// Getting key for the cipher object 
const key = crypto.scryptSync(password, 'salt', 24); 
  
// Creating and initializg the static iv 
const iv = Buffer.alloc(16, 0); 
  
// Creating and initializng the cipher object 
const cipher = crypto.createCipheriv(algorithm, key, iv); 
  
// Updating the cipher with the data 
// by using update() method 
let encrypted = cipher.update( 
    'some clear text data', 'utf8', 'hex'); 
  
// Getting the buffer data of cipher  
encrypted += cipher.final('hex'); 
  
// Display the result 
console.log(encrypted);

輸出:

e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa

範例2: 文件名:index.js

Javascript

// Node.js program to demonstrate the 
// cipher.update() method 
  
// Importing crypto module 
const crypto = require('crypto'); 
  
// Creating and initializng algorith and password 
const algorithm = 'aes-192-cbc'; 
const password = 'Password used to generate key'; 
  
// Getting key for cipher object 
crypto.scrypt(password, 'salt', 24, 
    { N:512 }, (err, key) => { 
        if (err) throw err; 
  
        // Creating and initializg the static iv 
        const iv = Buffer.alloc(16, 0); 
  
        // Creating and initializng the cipher object 
        const cipher = crypto 
            .createCipheriv(algorithm, key, iv); 
  
        // Updating the cipher with the data 
        // by using update() method 
        let encrypted = cipher.update( 
            'some clear text data', 'utf8', 'hex'); 
  
        // Getting the buffer data of cipher   
        encrypted += cipher.final('hex'); 
  
        // Display the result 
        console.log(encrypted); 
    });

輸出:

5850288b1848440f0c410400403f7b456293229b5231c17d2b83b602f252714b

使用以下命令運行index.js文件:

node index.js

參考: https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_cipher_update_data_inputencoding_outputencoding

相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js cipher.update() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。