pbes2kw.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { encode as b64u } from '../util/base64url.js';
  2. import * as aeskw from './aeskw.js';
  3. import { checkEncCryptoKey } from './crypto_key.js';
  4. import { concat, encode } from './buffer_utils.js';
  5. import { JWEInvalid } from '../util/errors.js';
  6. function getCryptoKey(key, alg) {
  7. if (key instanceof Uint8Array) {
  8. return crypto.subtle.importKey('raw', key, 'PBKDF2', false, [
  9. 'deriveBits',
  10. ]);
  11. }
  12. checkEncCryptoKey(key, alg, 'deriveBits');
  13. return key;
  14. }
  15. const concatSalt = (alg, p2sInput) => concat(encode(alg), Uint8Array.of(0x00), p2sInput);
  16. async function deriveKey(p2s, alg, p2c, key) {
  17. if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
  18. throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');
  19. }
  20. const salt = concatSalt(alg, p2s);
  21. const keylen = parseInt(alg.slice(13, 16), 10);
  22. const subtleAlg = {
  23. hash: `SHA-${alg.slice(8, 11)}`,
  24. iterations: p2c,
  25. name: 'PBKDF2',
  26. salt,
  27. };
  28. const cryptoKey = await getCryptoKey(key, alg);
  29. return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
  30. }
  31. export async function wrap(alg, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
  32. const derived = await deriveKey(p2s, alg, p2c, key);
  33. const encryptedKey = await aeskw.wrap(alg.slice(-6), derived, cek);
  34. return { encryptedKey, p2c, p2s: b64u(p2s) };
  35. }
  36. export async function unwrap(alg, key, encryptedKey, p2c, p2s) {
  37. const derived = await deriveKey(p2s, alg, p2c, key);
  38. return aeskw.unwrap(alg.slice(-6), derived, encryptedKey);
  39. }