UNPKG

cose-kit

Version:

This is an early prototype of a RFC8152 COSE library for node.js.

91 lines (90 loc) 3.23 kB
import verify from "#runtime/verify.js"; import sign from '#runtime/sign.js'; import { addExtension, encoder } from '../cbor.js'; import { WithHeaders } from './WithHeaders.js'; import { headers, macAlgs, macAlgsToValue } from '../headers.js'; import { areEqual, fromUTF8 } from "../lib/buffer_utils.js"; export class Mac0 extends WithHeaders { constructor(protectedHeaders, unprotectedHeaders, payload, tag) { super(protectedHeaders, unprotectedHeaders); this.payload = payload; this.tag = tag; } static createMAC0(protectedHeaders, applicationHeaders, payload) { return encoder.encode([ 'MAC0', protectedHeaders, applicationHeaders, payload, ]); } getContentForEncoding() { return [ this.encodedProtectedHeaders, this.unprotectedHeaders, this.payload, this.tag, ]; } encode() { return encoder.encode(this); } async verify(key, externalAAD = new Uint8Array(), detachedPayload) { if (!key) { throw new Error('key not found'); } const mac0Structure = Mac0.createMAC0(this.encodedProtectedHeaders || new Uint8Array(), externalAAD, detachedPayload !== null && detachedPayload !== void 0 ? detachedPayload : this.payload); if (!this.algName) { throw new Error('unknown algorithm: ' + this.alg); } return verify(this.algName, key, this.tag, mac0Structure); } get alg() { return this.protectedHeaders.get(headers.alg) || this.unprotectedHeaders.get(headers.alg); } get algName() { var _a; return this.alg ? (_a = macAlgs.get(this.alg)) === null || _a === void 0 ? void 0 : _a.name : undefined; } hasSupportedAlg() { return !!this.algName; } areEqual(mac0) { return areEqual(this.tag, mac0.tag); } static async create(protectedHeaders, unprotectedHeaders, payload, key) { const { alg } = protectedHeaders; const encodedProtectedHeaders = encoder.encode(new Map(Object.entries(protectedHeaders).map(([k, v]) => { if (k === 'alg') { v = macAlgsToValue.get(v); } else if (typeof v === 'string') { v = fromUTF8(v); } return [headers[k], v]; }))); const unprotectedHeadersMap = new Map(Object.entries(unprotectedHeaders || {}).map(([k, v]) => { if (typeof v === 'string') { v = fromUTF8(v); } return [headers[k], v]; })); const toBeSigned = Mac0.createMAC0(encodedProtectedHeaders, new Uint8Array(), payload); if (!alg) { throw new Error('The alg header must be set.'); } const tag = await sign(alg, key, toBeSigned); return new Mac0(encodedProtectedHeaders, unprotectedHeadersMap, payload, tag); } } addExtension({ Class: Mac0, tag: 17, encode(instance, encodeFn) { return encodeFn(instance.getContentForEncoding()); }, decode: (data) => { return new Mac0(data[0], data[1], data[2], data[3]); } });