Open In App

Node.js cipher.setAutoPadding() Method

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss about the setAutoPadding() method in the cipher class of the crypto module in Node JS. This method is used to automatically add padding to the input data of the appropriate size. To disable the padding, one can use cipher.setAutoPadding() with the false parameter.

Note: This method must be called before the final method.

Syntax:

cipher.setAutoPadding( autoPadding )

Parameter: This method accepts a single parameter as mentioned above and discussed below:

  • autoPadding: It is used to specify if automatic padding has to be used.

Example 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');
    });


Output:

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

Example 2: In this example, we called the setAutoPadding method after the final method. If you call this after the final method we got an error.

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));
    });


Output:

throw new ERR_CRYPTO_INVALID_STATE('setAutoPadding');

Reference: https://nodejs.org/api/crypto.html#ciphersetautopadding



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads