The Node.js crypto.createSign
method is used to create a sign object that uses the stated algorithms. The crypto
create sign method will create and return a sign object that uses the passed algorithm in the passed parameter.
You can use the name of the signature algorithms, such as RHA-SHA256
, instead of a digest algorithm to create a sign instance, but only in some cases.
crypto.createSign( algorithm, options )
The parameters as described in the snippet above are algorithm and options.
The algorithm
parameter takes the input for the algorithm name to be used while the sign object or instance is created.
The options
parameter is an optional parameter that can be used to control the stream behaviour.
crypto
createSign methodFirst, create a file with a name such as createSign.js. The .js is the file extension name that indicates that the file is a JavaScript file. After the file is created, run the commands in the code snippet described below.
// Node.js program to demonstrate the use of createSign() method// Importing the crypto moduleconst crypto = require('crypto');// Creating sign object with the input algorithmconst sign = crypto.createSign('SHA256');// Returning the sign objectconsole.log(sign);
Another example of how to use the Node.js createSign method is described in the code snippet below.
// Node.js program to demonstrate the use of createSign() method// Importing the crypto moduleconst crypto = require('crypto');// Creating sign object with the input algorithmconst sign = crypto.createSign('SHA256');// Returning the sign objectconsole.log(sign.write('Welcome to Tutorials Point'));
The snippet above is expected to have the output described below.
C:\home\node>> node createSign.js true
crypto.createSign(algorithm[, options])
The crypto.createSign options
method creates and returns a sign object that uses the given algorithm. You can use crypto.getHashes()
to obtain the names of the available digest algorithms. The optional options argument controls the stream.Writable
behavior.
In some cases, a Sign
instance can be created using the name of a signature algorithm, such as RSA-SHA256
, instead of a digest algorithm. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as ecdsa-with-SHA256
, so it is best to always use digest algorithm names.
createSign
function in crypto
The following snippet shows comprehensive guidelines on how to use the create sign function method in crypto
:
function rs256Jwt(header, payload, key) {if ( ! header.alg) {throw new Error("missing alg");}if (header.alg == 'RS256') {let signer = crypto.createSign('sha256');let signatureBase = [header, payload].map( x => b64(JSON.stringify(x)) ).join('.');signer.update(signatureBase);return signatureBase + '.' + toBase64Url(signer.sign(key, 'base64'));}throw new Error('unhandled alg: ' + header.alg);}