aeskw.js 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. import bogusWebCrypto from './bogus.js';
  2. import crypto, { isCryptoKey } from './webcrypto.js';
  3. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  4. import invalidKeyInput from '../lib/invalid_key_input.js';
  5. import { types } from './is_key_like.js';
  6. function checkKeySize(key, alg) {
  7. if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
  8. throw new TypeError(`Invalid key size for alg: ${alg}`);
  9. }
  10. }
  11. function getCryptoKey(key, alg, usage) {
  12. if (isCryptoKey(key)) {
  13. checkEncCryptoKey(key, alg, usage);
  14. return key;
  15. }
  16. if (key instanceof Uint8Array) {
  17. return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);
  18. }
  19. throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
  20. }
  21. export const wrap = async (alg, key, cek) => {
  22. const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');
  23. checkKeySize(cryptoKey, alg);
  24. const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
  25. return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));
  26. };
  27. export const unwrap = async (alg, key, encryptedKey) => {
  28. const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');
  29. checkKeySize(cryptoKey, alg);
  30. const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto);
  31. return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
  32. };