encrypt.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { concat, uint64be } from '../lib/buffer_utils.js';
  2. import checkIvLength from '../lib/check_iv_length.js';
  3. import checkCekLength from './check_cek_length.js';
  4. import crypto, { isCryptoKey } from './webcrypto.js';
  5. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  6. import invalidKeyInput from '../lib/invalid_key_input.js';
  7. import { JOSENotSupported } from '../util/errors.js';
  8. import { types } from './is_key_like.js';
  9. async function cbcEncrypt(enc, plaintext, cek, iv, aad) {
  10. if (!(cek instanceof Uint8Array)) {
  11. throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));
  12. }
  13. const keySize = parseInt(enc.slice(1, 4), 10);
  14. const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']);
  15. const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {
  16. hash: `SHA-${keySize << 1}`,
  17. name: 'HMAC',
  18. }, false, ['sign']);
  19. const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
  20. iv,
  21. name: 'AES-CBC',
  22. }, encKey, plaintext));
  23. const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
  24. const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));
  25. return { ciphertext, tag };
  26. }
  27. async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
  28. let encKey;
  29. if (cek instanceof Uint8Array) {
  30. encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);
  31. }
  32. else {
  33. checkEncCryptoKey(cek, enc, 'encrypt');
  34. encKey = cek;
  35. }
  36. const encrypted = new Uint8Array(await crypto.subtle.encrypt({
  37. additionalData: aad,
  38. iv,
  39. name: 'AES-GCM',
  40. tagLength: 128,
  41. }, encKey, plaintext));
  42. const tag = encrypted.slice(-16);
  43. const ciphertext = encrypted.slice(0, -16);
  44. return { ciphertext, tag };
  45. }
  46. const encrypt = async (enc, plaintext, cek, iv, aad) => {
  47. if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
  48. throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));
  49. }
  50. checkIvLength(enc, iv);
  51. switch (enc) {
  52. case 'A128CBC-HS256':
  53. case 'A192CBC-HS384':
  54. case 'A256CBC-HS512':
  55. if (cek instanceof Uint8Array)
  56. checkCekLength(cek, parseInt(enc.slice(-3), 10));
  57. return cbcEncrypt(enc, plaintext, cek, iv, aad);
  58. case 'A128GCM':
  59. case 'A192GCM':
  60. case 'A256GCM':
  61. if (cek instanceof Uint8Array)
  62. checkCekLength(cek, parseInt(enc.slice(1, 4), 10));
  63. return gcmEncrypt(enc, plaintext, cek, iv, aad);
  64. default:
  65. throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
  66. }
  67. };
  68. export default encrypt;