aeskw.js 1.2 KB

12345678910111213141516171819202122232425
  1. import { checkEncCryptoKey } from './crypto_key.js';
  2. function checkKeySize(key, alg) {
  3. if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
  4. throw new TypeError(`Invalid key size for alg: ${alg}`);
  5. }
  6. }
  7. function getCryptoKey(key, alg, usage) {
  8. if (key instanceof Uint8Array) {
  9. return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);
  10. }
  11. checkEncCryptoKey(key, alg, usage);
  12. return key;
  13. }
  14. export async function wrap(alg, key, cek) {
  15. const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');
  16. checkKeySize(cryptoKey, alg);
  17. const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);
  18. return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));
  19. }
  20. export async function unwrap(alg, key, encryptedKey) {
  21. const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');
  22. checkKeySize(cryptoKey, alg);
  23. const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', { hash: 'SHA-256', name: 'HMAC' }, true, ['sign']);
  24. return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
  25. }