encrypt.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. import { FlattenedEncrypt } from '../flattened/encrypt.js';
  2. import { unprotected, assertNotSet } from '../../lib/helpers.js';
  3. import { JOSENotSupported, JWEInvalid } from '../../util/errors.js';
  4. import { generateCek } from '../../lib/content_encryption.js';
  5. import { isDisjoint } from '../../lib/type_checks.js';
  6. import { encryptKeyManagement } from '../../lib/key_management.js';
  7. import { encode as b64u } from '../../util/base64url.js';
  8. import { validateCrit } from '../../lib/validate_crit.js';
  9. import { normalizeKey } from '../../lib/normalize_key.js';
  10. import { checkKeyType } from '../../lib/check_key_type.js';
  11. class IndividualRecipient {
  12. #parent;
  13. unprotectedHeader;
  14. keyManagementParameters;
  15. key;
  16. options;
  17. constructor(enc, key, options) {
  18. this.#parent = enc;
  19. this.key = key;
  20. this.options = options;
  21. }
  22. setUnprotectedHeader(unprotectedHeader) {
  23. assertNotSet(this.unprotectedHeader, 'setUnprotectedHeader');
  24. this.unprotectedHeader = unprotectedHeader;
  25. return this;
  26. }
  27. setKeyManagementParameters(parameters) {
  28. assertNotSet(this.keyManagementParameters, 'setKeyManagementParameters');
  29. this.keyManagementParameters = parameters;
  30. return this;
  31. }
  32. addRecipient(...args) {
  33. return this.#parent.addRecipient(...args);
  34. }
  35. encrypt(...args) {
  36. return this.#parent.encrypt(...args);
  37. }
  38. done() {
  39. return this.#parent;
  40. }
  41. }
  42. export class GeneralEncrypt {
  43. #plaintext;
  44. #recipients = [];
  45. #protectedHeader;
  46. #unprotectedHeader;
  47. #aad;
  48. constructor(plaintext) {
  49. this.#plaintext = plaintext;
  50. }
  51. addRecipient(key, options) {
  52. const recipient = new IndividualRecipient(this, key, { crit: options?.crit });
  53. this.#recipients.push(recipient);
  54. return recipient;
  55. }
  56. setProtectedHeader(protectedHeader) {
  57. assertNotSet(this.#protectedHeader, 'setProtectedHeader');
  58. this.#protectedHeader = protectedHeader;
  59. return this;
  60. }
  61. setSharedUnprotectedHeader(sharedUnprotectedHeader) {
  62. assertNotSet(this.#unprotectedHeader, 'setSharedUnprotectedHeader');
  63. this.#unprotectedHeader = sharedUnprotectedHeader;
  64. return this;
  65. }
  66. setAdditionalAuthenticatedData(aad) {
  67. this.#aad = aad;
  68. return this;
  69. }
  70. async encrypt() {
  71. if (!this.#recipients.length) {
  72. throw new JWEInvalid('at least one recipient must be added');
  73. }
  74. if (this.#recipients.length === 1) {
  75. const [recipient] = this.#recipients;
  76. const flattened = await new FlattenedEncrypt(this.#plaintext)
  77. .setAdditionalAuthenticatedData(this.#aad)
  78. .setProtectedHeader(this.#protectedHeader)
  79. .setSharedUnprotectedHeader(this.#unprotectedHeader)
  80. .setUnprotectedHeader(recipient.unprotectedHeader)
  81. .encrypt(recipient.key, { ...recipient.options });
  82. const jwe = {
  83. ciphertext: flattened.ciphertext,
  84. iv: flattened.iv,
  85. recipients: [{}],
  86. tag: flattened.tag,
  87. };
  88. if (flattened.aad)
  89. jwe.aad = flattened.aad;
  90. if (flattened.protected)
  91. jwe.protected = flattened.protected;
  92. if (flattened.unprotected)
  93. jwe.unprotected = flattened.unprotected;
  94. if (flattened.encrypted_key)
  95. jwe.recipients[0].encrypted_key = flattened.encrypted_key;
  96. if (flattened.header)
  97. jwe.recipients[0].header = flattened.header;
  98. return jwe;
  99. }
  100. let enc;
  101. for (let i = 0; i < this.#recipients.length; i++) {
  102. const recipient = this.#recipients[i];
  103. if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, recipient.unprotectedHeader)) {
  104. throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');
  105. }
  106. const joseHeader = {
  107. ...this.#protectedHeader,
  108. ...this.#unprotectedHeader,
  109. ...recipient.unprotectedHeader,
  110. };
  111. const { alg } = joseHeader;
  112. if (typeof alg !== 'string' || !alg) {
  113. throw new JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');
  114. }
  115. if (alg === 'dir' || alg === 'ECDH-ES') {
  116. throw new JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');
  117. }
  118. if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {
  119. throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');
  120. }
  121. if (!enc) {
  122. enc = joseHeader.enc;
  123. }
  124. else if (enc !== joseHeader.enc) {
  125. throw new JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');
  126. }
  127. validateCrit(JWEInvalid, new Map(), recipient.options.crit, this.#protectedHeader, joseHeader);
  128. if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {
  129. throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
  130. }
  131. if (joseHeader.zip !== undefined && !this.#protectedHeader?.zip) {
  132. throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
  133. }
  134. }
  135. const cek = generateCek(enc);
  136. const jwe = {
  137. ciphertext: '',
  138. recipients: [],
  139. };
  140. for (let i = 0; i < this.#recipients.length; i++) {
  141. const recipient = this.#recipients[i];
  142. const target = {};
  143. jwe.recipients.push(target);
  144. if (i === 0) {
  145. const flattened = await new FlattenedEncrypt(this.#plaintext)
  146. .setAdditionalAuthenticatedData(this.#aad)
  147. .setContentEncryptionKey(cek)
  148. .setProtectedHeader(this.#protectedHeader)
  149. .setSharedUnprotectedHeader(this.#unprotectedHeader)
  150. .setUnprotectedHeader(recipient.unprotectedHeader)
  151. .setKeyManagementParameters(recipient.keyManagementParameters)
  152. .encrypt(recipient.key, {
  153. ...recipient.options,
  154. [unprotected]: true,
  155. });
  156. jwe.ciphertext = flattened.ciphertext;
  157. jwe.iv = flattened.iv;
  158. jwe.tag = flattened.tag;
  159. if (flattened.aad)
  160. jwe.aad = flattened.aad;
  161. if (flattened.protected)
  162. jwe.protected = flattened.protected;
  163. if (flattened.unprotected)
  164. jwe.unprotected = flattened.unprotected;
  165. target.encrypted_key = flattened.encrypted_key;
  166. if (flattened.header)
  167. target.header = flattened.header;
  168. continue;
  169. }
  170. const alg = recipient.unprotectedHeader?.alg ||
  171. this.#protectedHeader?.alg ||
  172. this.#unprotectedHeader?.alg;
  173. checkKeyType(alg === 'dir' ? enc : alg, recipient.key, 'encrypt');
  174. const k = await normalizeKey(recipient.key, alg);
  175. const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
  176. target.encrypted_key = b64u(encryptedKey);
  177. if (recipient.unprotectedHeader || parameters)
  178. target.header = { ...recipient.unprotectedHeader, ...parameters };
  179. }
  180. return jwe;
  181. }
  182. }