aeskw.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Buffer } from 'buffer';
  2. import { KeyObject, createDecipheriv, createCipheriv, createSecretKey } from 'crypto';
  3. import { JOSENotSupported } from '../util/errors.js';
  4. import { concat } from '../lib/buffer_utils.js';
  5. import { isCryptoKey } from './webcrypto.js';
  6. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  7. import isKeyObject from './is_key_object.js';
  8. import invalidKeyInput from '../lib/invalid_key_input.js';
  9. import supported from './ciphers.js';
  10. import { types } from './is_key_like.js';
  11. function checkKeySize(key, alg) {
  12. if (key.symmetricKeySize << 3 !== parseInt(alg.slice(1, 4), 10)) {
  13. throw new TypeError(`Invalid key size for alg: ${alg}`);
  14. }
  15. }
  16. function ensureKeyObject(key, alg, usage) {
  17. if (isKeyObject(key)) {
  18. return key;
  19. }
  20. if (key instanceof Uint8Array) {
  21. return createSecretKey(key);
  22. }
  23. if (isCryptoKey(key)) {
  24. checkEncCryptoKey(key, alg, usage);
  25. return KeyObject.from(key);
  26. }
  27. throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
  28. }
  29. export const wrap = (alg, key, cek) => {
  30. const size = parseInt(alg.slice(1, 4), 10);
  31. const algorithm = `aes${size}-wrap`;
  32. if (!supported(algorithm)) {
  33. throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
  34. }
  35. const keyObject = ensureKeyObject(key, alg, 'wrapKey');
  36. checkKeySize(keyObject, alg);
  37. const cipher = createCipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6));
  38. return concat(cipher.update(cek), cipher.final());
  39. };
  40. export const unwrap = (alg, key, encryptedKey) => {
  41. const size = parseInt(alg.slice(1, 4), 10);
  42. const algorithm = `aes${size}-wrap`;
  43. if (!supported(algorithm)) {
  44. throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
  45. }
  46. const keyObject = ensureKeyObject(key, alg, 'unwrapKey');
  47. checkKeySize(keyObject, alg);
  48. const cipher = createDecipheriv(algorithm, keyObject, Buffer.alloc(8, 0xa6));
  49. return concat(cipher.update(encryptedKey), cipher.final());
  50. };