Node.js cipher.setAutoPadding() 方法
在本篇文章中,我们将讨论 Node.js 中 crypto 模块中 cipher 类的 setAutoPadding() 方法。该方法用于自动在输入数据中添加适当大小的填充。若要禁用填充,可以使用 cipher.setAutoPadding() 方法,并传入 false 参数。
注意: 该方法必须在最后的方法之前调用。
语法:
cipher.setAutoPadding( autoPadding )
参数:
此方法接受一个单一参数,如上所述并在下面讨论:
- autoPadding:用于指定是否需要使用自动填充。
示例1:
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: 在这个示例中,我们在最后一个方法之后调用了setAutoPadding方法。如果你在最后一个方法之后调用这个方法,我们会得到一个错误。
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