What is Crypto.constants in node?
The crypto.constants method returns an Object containing constants commonly used in different security operations in the crypto module.
Syntax
The syntax is: crypto.constants
Below is an example that prints all the commonly used constants used in the crypto module.
// Importing the crypto libraryconst crypto = require("crypto")// Storing the constants inside the variablelet constants = crypto.constants// Printing the constantsconsole.log(constants)
On your local machine, you can put the above code in an index.js file and run node index.js on the terminal to see the results. Even better, you click run on the above code to see the results.
As defined earlier, the output of the code is an object with keys that correspond to the different crypto constants available.
Crypto.constants make it easy to call and use different constants required by other crypto module methods in encryption and decryption. crypto.constants can primarily be called and used by other crypto methods.
Below are some sample Javascript code snippets that use crypto.constants.
Code 1
static privateDecrypt(key, data) {
return crypto.privateDecrypt({
key: key.toPem(),
padding: crypto.constants.RSA_PKCS1_PADDING,
}, data);
}
Source code can be viewed on git at
Code 1 (above) is an implementation of the private decryption that uses crypto.privateDecrypt and takes an object argument with one of its properties being a constant. In this case, RSA_NO_PADDING.
Code 2
const rsaEncrypt = (buffer, key) => {
buffer = Buffer.concat([Buffer.alloc(128 - buffer.length), buffer])
return crypto.publicEncrypt({key: key, padding: crypto.constants.RSA_NO_PADDING}, buffer)
}
Source code can be viewed on git at
Just as in code 1, code 2 is another security implementation that uses one of the crypto module methods (crypto.publicEncrypt). Once again, the crypto constant RSA_NO_PADDING is called to use here.
Code 3
static publicEncrypt(key, data) {
return crypto.publicEncrypt({
key: key.toPem(),
padding: crypto.constants.RSA_PKCS1_PADDING,
}, data);
}
Source code can be viewed on git at
Code 3, just like code 2, is another encryption operation that uses crypto.publicEncrypt. But this time, the constant RSA_PKCS1_PADDING is called on and utilized.
As we can see from the code snippets above, some padding constants (RSA_PKCS1_PADDING and RSA_NO_PADDING) were utilized. These constants can be seen from the output when code 1 of this article is run.
Just as we have indicated in the earlier parts of this article, several other crypto.constants can be called on. These will be based on the crypto operation to be performed in node and the constant is required.