pbes2kw.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import random from './random.js';
  2. import { p2s as concatSalt } from '../lib/buffer_utils.js';
  3. import { encode as base64url } from './base64url.js';
  4. import { wrap, unwrap } from './aeskw.js';
  5. import checkP2s from '../lib/check_p2s.js';
  6. import crypto, { isCryptoKey } from './webcrypto.js';
  7. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  8. import invalidKeyInput from '../lib/invalid_key_input.js';
  9. import { types } from './is_key_like.js';
  10. function getCryptoKey(key, alg) {
  11. if (key instanceof Uint8Array) {
  12. return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);
  13. }
  14. if (isCryptoKey(key)) {
  15. checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');
  16. return key;
  17. }
  18. throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
  19. }
  20. async function deriveKey(p2s, alg, p2c, key) {
  21. checkP2s(p2s);
  22. const salt = concatSalt(alg, p2s);
  23. const keylen = parseInt(alg.slice(13, 16), 10);
  24. const subtleAlg = {
  25. hash: `SHA-${alg.slice(8, 11)}`,
  26. iterations: p2c,
  27. name: 'PBKDF2',
  28. salt,
  29. };
  30. const wrapAlg = {
  31. length: keylen,
  32. name: 'AES-KW',
  33. };
  34. const cryptoKey = await getCryptoKey(key, alg);
  35. if (cryptoKey.usages.includes('deriveBits')) {
  36. return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
  37. }
  38. if (cryptoKey.usages.includes('deriveKey')) {
  39. return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']);
  40. }
  41. throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"');
  42. }
  43. export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {
  44. const derived = await deriveKey(p2s, alg, p2c, key);
  45. const encryptedKey = await wrap(alg.slice(-6), derived, cek);
  46. return { encryptedKey, p2c, p2s: base64url(p2s) };
  47. };
  48. export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
  49. const derived = await deriveKey(p2s, alg, p2c, key);
  50. return unwrap(alg.slice(-6), derived, encryptedKey);
  51. };