decrypt.js 1.0 KB

123456789101112131415161718192021222324252627
  1. import { flattenedDecrypt } from '../flattened/decrypt.js';
  2. import { JWEInvalid } from '../../util/errors.js';
  3. import { decoder } from '../../lib/buffer_utils.js';
  4. export async function compactDecrypt(jwe, key, options) {
  5. if (jwe instanceof Uint8Array) {
  6. jwe = decoder.decode(jwe);
  7. }
  8. if (typeof jwe !== 'string') {
  9. throw new JWEInvalid('Compact JWE must be a string or Uint8Array');
  10. }
  11. const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');
  12. if (length !== 5) {
  13. throw new JWEInvalid('Invalid Compact JWE');
  14. }
  15. const decrypted = await flattenedDecrypt({
  16. ciphertext,
  17. iv: (iv || undefined),
  18. protected: protectedHeader || undefined,
  19. tag: (tag || undefined),
  20. encrypted_key: encryptedKey || undefined,
  21. }, key, options);
  22. const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };
  23. if (typeof key === 'function') {
  24. return { ...result, key: decrypted.key };
  25. }
  26. return result;
  27. }