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


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


在本文中,我們將討論 Node JS 中 crypto 模塊的 cipher 類中的 setAutoPadding() 方法。該方法用於自動為適當大小的輸入數據添加填充。要禁用填充,可以使用帶有 false 參數的 cipher.setAutoPadding()。

注意:該方法必須在最終方法之前調用。

用法:

cipher.setAutoPadding( autoPadding )

參數:該方法接受如上所述和下麵討論的單個參數:

  • autoPadding: 它用於指定是否必須使用自動填充。

示例 1:

Javascript


const crypto = require('crypto'); 
  
// Creating and initializing algorithm 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 initializing the static iv 
        const iv = Buffer.alloc(16, 0); 
  
        // Creating and initializing the cipher object 
        const cipher = crypto.createCipheriv(algorithm, key, iv); 
  
        // Getting buffer value 
        // by using final() method 
  
        // Using the cipher.setAutoPadding() method 
        // with the false parameter 
        console.log(cipher.setAutoPadding(false)); 
        let value = cipher.final('hex'); 
    });

輸出:

Cipheriv {
 _decoder: null,
 _options: undefined,
 [Symbol(kHandle)]: CipherBase {}
}

示例 2:在這個例子中,我們在final方法之後調用了setAutoPadding方法。如果您在最終方法之後調用此方法,我們會收到錯誤。

Javascript


const crypto = require('crypto'); 
  
// Creating and initializing algorithm 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 initializing the static iv 
        const iv = Buffer.alloc(16, 0); 
  
        // Creating and initializing the cipher object 
        const cipher = crypto.createCipheriv(algorithm, key, iv); 
  
        // Getting buffer value 
        // by using final() method 
  
        // Calling the setAutoPadding() method  
        // after the final method  
        let value = cipher.final('hex'); 
        console.log(cipher.setAutoPadding(false)); 
    });

輸出:

throw new ERR_CRYPTO_INVALID_STATE('setAutoPadding');

參考: https://nodejs.org/api/crypto.html#ciphersetautopadding



相關用法


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