On this page

C

Mac

History
class Mac extends stream.Transform

The Mac class computes message authentication codes using MAC implementations supplied by OpenSSL providers. It can be used in one of two ways:

  • As a stream that is both readable and writable, where data is written and one authentication tag is produced on the readable side when the writable side ends; or
  • By calling mac.update() one or more times followed by mac.final().

Instances of Mac are created using crypto.createMac(). The Mac class is not exported directly by the node:crypto module.

Calling mac.end() without first writing data computes the authentication tag for an empty message. If the selected MAC produces a zero-byte tag, such as when a provider accepts outputLength: 0, the readable side ends without emitting a data chunk because Node.js streams do not emit zero-length chunks. When using mac.final() instead, it returns a zero-length Buffer or an empty encoded string.

mac.end() and mac.final() are alternative terminal operations and must not both be called on the same object. A Mac object cannot be used again after either operation attempts finalization or after an underlying MAC update fails.

Example: Using mac.update() and mac.final():

const { createMac, randomBytes } = await import('node:crypto');

const key = randomBytes(16);
const mac = createMac('CMAC', key, {
  cipher: 'AES-128-CBC',
});

mac.update('some data to authenticate');
console.log(mac.final('hex'));
M

mac.final

History
mac.final(outputEncoding?): Buffer | string
Attributes
outputEncoding:string
The encoding of the return value.
Returns:Buffer | string

Completes the MAC computation and returns the authentication tag. If outputEncoding is omitted or is 'buffer', a Buffer is returned. Otherwise, a string is returned.

To verify an authentication tag, compare equal-length Buffer values using crypto.timingSafeEqual().

The Mac object cannot be used again after finalization is attempted, including when finalization fails. Later calls to mac.update() or mac.final() throw ERR_CRYPTO_MAC_FINALIZED.

M

mac.update

History
mac.update(data, inputEncoding?): Mac
Attributes
inputEncoding:string
The encoding of the data string.
Returns:Mac

Updates the MAC with data and returns the Mac object so that calls can be chained. When data is a string, inputEncoding defaults to 'utf8'. When data is a Buffer, TypedArray, or DataView, inputEncoding is ignored.

This method can be called multiple times before finalization. If an underlying MAC update fails, the Mac object cannot be used again. Calling this method after a previous underlying MAC update failure or after finalization throws ERR_CRYPTO_MAC_FINALIZED.