decrypt.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { decode as b64u } from '../../util/base64url.js';
  2. import { decrypt } from '../../lib/content_encryption.js';
  3. import { decodeBase64url } from '../../lib/helpers.js';
  4. import { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';
  5. import { isDisjoint } from '../../lib/type_checks.js';
  6. import { isObject } from '../../lib/type_checks.js';
  7. import { decryptKeyManagement } from '../../lib/key_management.js';
  8. import { decoder, concat, encode } from '../../lib/buffer_utils.js';
  9. import { generateCek } from '../../lib/content_encryption.js';
  10. import { validateCrit } from '../../lib/validate_crit.js';
  11. import { validateAlgorithms } from '../../lib/validate_algorithms.js';
  12. import { normalizeKey } from '../../lib/normalize_key.js';
  13. import { checkKeyType } from '../../lib/check_key_type.js';
  14. import { decompress } from '../../lib/deflate.js';
  15. export async function flattenedDecrypt(jwe, key, options) {
  16. if (!isObject(jwe)) {
  17. throw new JWEInvalid('Flattened JWE must be an object');
  18. }
  19. if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {
  20. throw new JWEInvalid('JOSE Header missing');
  21. }
  22. if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {
  23. throw new JWEInvalid('JWE Initialization Vector incorrect type');
  24. }
  25. if (typeof jwe.ciphertext !== 'string') {
  26. throw new JWEInvalid('JWE Ciphertext missing or incorrect type');
  27. }
  28. if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {
  29. throw new JWEInvalid('JWE Authentication Tag incorrect type');
  30. }
  31. if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {
  32. throw new JWEInvalid('JWE Protected Header incorrect type');
  33. }
  34. if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {
  35. throw new JWEInvalid('JWE Encrypted Key incorrect type');
  36. }
  37. if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {
  38. throw new JWEInvalid('JWE AAD incorrect type');
  39. }
  40. if (jwe.header !== undefined && !isObject(jwe.header)) {
  41. throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');
  42. }
  43. if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {
  44. throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');
  45. }
  46. let parsedProt;
  47. if (jwe.protected) {
  48. try {
  49. const protectedHeader = b64u(jwe.protected);
  50. parsedProt = JSON.parse(decoder.decode(protectedHeader));
  51. }
  52. catch {
  53. throw new JWEInvalid('JWE Protected Header is invalid');
  54. }
  55. }
  56. if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {
  57. throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');
  58. }
  59. const joseHeader = {
  60. ...parsedProt,
  61. ...jwe.header,
  62. ...jwe.unprotected,
  63. };
  64. validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);
  65. if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {
  66. throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
  67. }
  68. if (joseHeader.zip !== undefined && !parsedProt?.zip) {
  69. throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
  70. }
  71. const { alg, enc } = joseHeader;
  72. if (typeof alg !== 'string' || !alg) {
  73. throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');
  74. }
  75. if (typeof enc !== 'string' || !enc) {
  76. throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');
  77. }
  78. const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);
  79. const contentEncryptionAlgorithms = options &&
  80. validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);
  81. if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||
  82. (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {
  83. throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
  84. }
  85. if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {
  86. throw new JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');
  87. }
  88. let encryptedKey;
  89. if (jwe.encrypted_key !== undefined) {
  90. encryptedKey = decodeBase64url(jwe.encrypted_key, 'encrypted_key', JWEInvalid);
  91. }
  92. let resolvedKey = false;
  93. if (typeof key === 'function') {
  94. key = await key(parsedProt, jwe);
  95. resolvedKey = true;
  96. }
  97. checkKeyType(alg === 'dir' ? enc : alg, key, 'decrypt');
  98. const k = await normalizeKey(key, alg);
  99. let cek;
  100. try {
  101. cek = await decryptKeyManagement(alg, k, encryptedKey, joseHeader, options);
  102. }
  103. catch (err) {
  104. if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {
  105. throw err;
  106. }
  107. cek = generateCek(enc);
  108. }
  109. let iv;
  110. let tag;
  111. if (jwe.iv !== undefined) {
  112. iv = decodeBase64url(jwe.iv, 'iv', JWEInvalid);
  113. }
  114. if (jwe.tag !== undefined) {
  115. tag = decodeBase64url(jwe.tag, 'tag', JWEInvalid);
  116. }
  117. const protectedHeader = jwe.protected !== undefined ? encode(jwe.protected) : new Uint8Array();
  118. let additionalData;
  119. if (jwe.aad !== undefined) {
  120. additionalData = concat(protectedHeader, encode('.'), encode(jwe.aad));
  121. }
  122. else {
  123. additionalData = protectedHeader;
  124. }
  125. const ciphertext = decodeBase64url(jwe.ciphertext, 'ciphertext', JWEInvalid);
  126. const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);
  127. const result = { plaintext };
  128. if (joseHeader.zip === 'DEF') {
  129. const maxDecompressedLength = options?.maxDecompressedLength ?? 250_000;
  130. if (maxDecompressedLength === 0) {
  131. throw new JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');
  132. }
  133. if (maxDecompressedLength !== Infinity &&
  134. (!Number.isSafeInteger(maxDecompressedLength) || maxDecompressedLength < 1)) {
  135. throw new TypeError('maxDecompressedLength must be 0, a positive safe integer, or Infinity');
  136. }
  137. result.plaintext = await decompress(plaintext, maxDecompressedLength).catch((cause) => {
  138. if (cause instanceof JWEInvalid)
  139. throw cause;
  140. throw new JWEInvalid('Failed to decompress plaintext', { cause });
  141. });
  142. }
  143. if (jwe.protected !== undefined) {
  144. result.protectedHeader = parsedProt;
  145. }
  146. if (jwe.aad !== undefined) {
  147. result.additionalAuthenticatedData = decodeBase64url(jwe.aad, 'aad', JWEInvalid);
  148. }
  149. if (jwe.unprotected !== undefined) {
  150. result.sharedUnprotectedHeader = jwe.unprotected;
  151. }
  152. if (jwe.header !== undefined) {
  153. result.unprotectedHeader = jwe.header;
  154. }
  155. if (resolvedKey) {
  156. return { ...result, key: k };
  157. }
  158. return result;
  159. }