类:Mac
🌐 Class: Mac
- 扩展自: <stream.Transform>
Mac 类使用 OpenSSL 提供的 MAC 实现来计算消息认证码。它可以通过两种方式使用:
🌐 The Mac class computes message authentication codes using MAC
implementations supplied by OpenSSL providers. It can be used in one of two
ways:
- 作为一个可读可写的 小溪,当可写端结束时,会在可读端生成一个认证标签;或者
- 通过先调用一次或多次
mac.update(),然后调用mac.final()。
Mac 的实例是使用 crypto.createMac() 创建的。Mac 类不会被 node:crypto 模块直接导出。
🌐 Instances of Mac are created using crypto.createMac(). The Mac class
is not exported directly by the node:crypto module.
在没有先写入数据的情况下调用 mac.end() 会计算一个空消息的认证标签。如果选择的 MAC 生成零字节标签,比如提供者接受 outputLength: 0 的情况,可读端不会发出数据块就结束了,因为 Node.js 流不会发出零长度块。使用 mac.final() 时,它会返回一个零长度的 Buffer 或一个空的编码字符串。
🌐 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() 和 mac.final() 是可替代的终端操作,不能在同一个对象上同时调用。在尝试完成操作或底层 MAC 更新失败后,Mac 对象不能再次使用。
例如:使用 mac.update() 和 mac.final():
🌐 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'));