aeskw.js 2.5 KB

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