UNPKG

cose-kit

Version:

**DEPRECATED:** Use [@auth0/cose](https://www.npmjs.com/package/@auth0/cose).

159 lines (158 loc) 7.46 kB
import { addExtension, encoder } from '../cbor.js'; import { COSEBase } from './COSEBase.js'; import * as errors from "../util/errors.js"; import validateAlgorithms from "../lib/validate_algorithms.js"; import { EncryptProtectedHeaders, EncryptionAlgorithmNames, Headers, UnprotectedHeaders } from '../headers.js'; import { decode } from "./decode.js"; import decrypt from '#runtime/decrypt.js'; import { COSEKeyParam } from '../key/index.js'; import { COSEKey } from "../key/COSEKey.js"; import { concat } from '../lib/buffer_utils.js'; import generateIv from '../lib/iv.js'; import encrypt from '#runtime/encrypt.js'; export class Encrypt extends COSEBase { constructor(protectedHeaders, unprotectedHeaders, ciphertext, recipients) { super(protectedHeaders, unprotectedHeaders); this.ciphertext = ciphertext; this.recipients = recipients; } static createAAD(protectedHeaders, externalAAD) { return encoder.encode([ 'Encrypt', protectedHeaders, externalAAD ]); } getContentForEncoding() { const mapRecipient = (r) => { var _a; const result = [ r.protectedHeaders, r.unprotectedHeaders, (_a = r.ciphertext) !== null && _a !== void 0 ? _a : new Uint8Array(), ]; if (r.recipients && Array.isArray(r.recipients)) { result.push(r.recipients.map(mapRecipient)); } return result; }; return [ this.encodedProtectedHeaders, this.unprotectedHeaders, this.ciphertext, this.recipients.map(mapRecipient), ]; } static decode(cose) { return decode(cose, Encrypt); } async decrypt(key, options) { var _a, _b, _c; if (this.recipients.length > 1 || this.recipients.some(r => r.unprotectedHeaders.get(Headers.Algorithm) !== -6)) { throw new Error('Multiple recipients or recipient with non-direct algorithm not supported'); } const ciphertextWithTag = (_a = options === null || options === void 0 ? void 0 : options.detachedPayload) !== null && _a !== void 0 ? _a : this.ciphertext; const aad = Encrypt.createAAD((_b = this.encodedProtectedHeaders) !== null && _b !== void 0 ? _b : new Uint8Array(), (_c = options === null || options === void 0 ? void 0 : options.externalAAD) !== null && _c !== void 0 ? _c : new Uint8Array()); if (!this.alg || !this.algName || !EncryptionAlgorithmNames.has(this.alg)) { throw new errors.COSEInvalid(`Unsupported encryption algorithm ${this.alg}`); } const algorithms = options && validateAlgorithms('algorithms', options.algorithms); if (algorithms && !algorithms.has(this.alg)) { throw new errors.COSEAlgNotAllowed(`[${Headers.Algorithm}] (algorithm) Header Parameter not allowed`); } let iv; if (this.unprotectedHeaders.has(Headers.IV) && this.unprotectedHeaders.has(Headers.PartialIV)) { throw new errors.COSEInvalid('IV and Partial IV must not both be present in the COSE message.'); } else if (this.unprotectedHeaders.has(Headers.PartialIV)) { if (!(key instanceof COSEKey) || !key.has(COSEKeyParam.BaseIV)) { throw new errors.COSEInvalid('Key must be a COSEKey instance with Base IV to use Partial IV'); } iv = concat(key.get(COSEKeyParam.BaseIV), this.unprotectedHeaders.get(Headers.PartialIV)); } else if (this.unprotectedHeaders.has(Headers.IV)) { iv = this.unprotectedHeaders.get(Headers.IV); } else { throw new errors.COSEInvalid('IV or Partial IV must be present in the COSE message.'); } const tag = ciphertextWithTag.slice(-16); const ciphertext = ciphertextWithTag.slice(0, -16); const decryptKey = key instanceof COSEKey ? (await key.toKeyLike()) : key; return decrypt(this.algName, decryptKey, ciphertext, iv, tag, aad); } get alg() { return this.protectedHeaders.get(Headers.Algorithm) || this.unprotectedHeaders.get(Headers.Algorithm); } get algName() { return this.alg ? EncryptionAlgorithmNames.get(this.alg) : undefined; } hasSupportedAlg() { return !!this.algName; } static async encrypt(protectedHeaders, unprotectedHeaders, content, key, externalAAD = new Uint8Array(), recipients) { if (recipients.length > 1 || recipients.some(r => r.unprotectedHeaders.get(Headers.Algorithm) !== -6)) { throw new Error('Multiple recipients or recipient with non-direct algorithm not supported'); } const wProtectedHeaders = EncryptProtectedHeaders.wrap(protectedHeaders); const alg = EncryptionAlgorithmNames.get(wProtectedHeaders.get(Headers.Algorithm)); if (!alg) { throw new Error(`The protected header [${Headers.Algorithm}] (Algorithm) must be valid.`); } const wUnprotectedHeaders = UnprotectedHeaders.wrap([...(unprotectedHeaders || [])]); let iv = wUnprotectedHeaders.get(Headers.IV); if (!iv) { const partialIV = wUnprotectedHeaders.get(Headers.PartialIV); if (partialIV) { if (!(key instanceof COSEKey) || !key.has(COSEKeyParam.BaseIV)) { throw new errors.COSEInvalid('Key must be a COSEKey instance with Base IV to use Partial IV'); } iv = concat(key.get(COSEKeyParam.BaseIV), partialIV); } else { iv = generateIv(alg); wUnprotectedHeaders.set(Headers.IV, iv); } } const aad = Encrypt.createAAD(encoder.encode(wProtectedHeaders.esMap), externalAAD); const encryptKey = key instanceof COSEKey ? (await key.toKeyLike()) : key; const { ciphertext, tag } = await encrypt(alg, content, encryptKey, iv, aad); const r = concat(ciphertext, tag); return new Encrypt(wProtectedHeaders.esMap, wUnprotectedHeaders.esMap, r, recipients); } } Encrypt.tag = 96; export class Recipient extends COSEBase { constructor(protectedHeaders, unprotectedHeaders, ciphertext, recipients) { super(protectedHeaders, unprotectedHeaders); this.ciphertext = ciphertext; this.recipients = recipients; } static create(protectedHeaders, unprotectedHeaders) { const wProtectedHeaders = EncryptProtectedHeaders.wrap(protectedHeaders); const wUnprotectedHeaders = UnprotectedHeaders.wrap(unprotectedHeaders); return new Recipient(wProtectedHeaders.esMap, wUnprotectedHeaders.esMap); } get alg() { return this.protectedHeaders.get(Headers.Algorithm) || this.unprotectedHeaders.get(Headers.Algorithm); } get algName() { return this.alg && this.alg !== -6 ? EncryptionAlgorithmNames.get(this.alg) : undefined; } hasSupportedAlg() { return !!this.algName; } } addExtension({ Class: Encrypt, tag: Encrypt.tag, encode(instance, encodeFn) { return encodeFn(instance.getContentForEncoding()); }, decode: (data) => { const recipients = data[3].map(rec => new Recipient(rec[0], rec[1], rec[2], rec[3])); return new Encrypt(data[0], data[1], data[2], recipients); } });