crypto APIs to create cryptographic HMAC content
The crypto module offers a set of APIs to create cryptographic HMAC content.
To access the APIs in the crypto module, use the
require('crypto') statement.
crypto.createHmac()
Creates and returns a hmac object, which is a cryptographic HMAC with the
algorithm and key.
- Syntax
crypto.createHmac(algorithm,key)- Parameters
-
- algorithm
- The case-sensitive name of the algorithm to use. The following values for the algorithm are
supported. The
hmac-prefix-naming is the same as the one without the prefix. In other words,hmac-sha1is the same assha1.hmac-sha1orsha1.hmac-sha256orsha256.hmac-sha512orsha512.hmac-sha224orsha224.hmac-sha384orsha384.hmac-ripemd160orripemd160.hmac-md5ormd5.
- key
- The shared secret key that to encrypt text. The key must be.
- A string object that refers to a configured object that also supports prefix usage in XSLT.
- A Buffer or Buffers object that contains Base64 encoded data of a key.
- An Object.
- A symmetric key whose JWK
'kty'member value is'oct'.
- Example
-
Use the
hmac-sha256algorithm and theAliceshared secret key object to do the HMAC. The result is Base64 encoded.var crypto = require('crypto'); var key = "Alice"; var hmac = crypto.createHmac('hmac-sha256', key); var input = "This is plaintext to hash"; var result = hmac.update(input).digest('base64'); session.output.write(result);
hmac.digest()
Calculates the digest of the data that is passed to the HMAC.
- Syntax
hmac.digest([encoding])- Parameters
-
- encoding
- The encoding of the resultant digest. The encoding can be
'hex'or'base64'. If no encoding is provided, a Buffer is returned. Thehmacobject cannot be used after the digest() method is called.
hmac.update()
Updates the content of the hmac object with the data, the encoding of which is
given in input encoding. This method can be called several times.
- Syntax
hmac.update(data[,encoding])- Parameters
-
- data
- The data to change in the digest.
- encoding
- The encoding of the data. The input_encoding can be
'utf8'or'ascii'. If no encoding is provided and the input is a string, an encoding of'utf8'is enforced. If data is a Buffer or Buffers, input encoding is ignored.