pbes2kw.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { promisify } from 'util';
  2. import { KeyObject, pbkdf2 as pbkdf2cb } from 'crypto';
  3. import random from './random.js';
  4. import { p2s as concatSalt } from '../lib/buffer_utils.js';
  5. import { encode as base64url } from './base64url.js';
  6. import { wrap, unwrap } from './aeskw.js';
  7. import checkP2s from '../lib/check_p2s.js';
  8. import { isCryptoKey } from './webcrypto.js';
  9. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  10. import isKeyObject from './is_key_object.js';
  11. import invalidKeyInput from '../lib/invalid_key_input.js';
  12. import { types } from './is_key_like.js';
  13. const pbkdf2 = promisify(pbkdf2cb);
  14. function getPassword(key, alg) {
  15. if (isKeyObject(key)) {
  16. return key.export();
  17. }
  18. if (key instanceof Uint8Array) {
  19. return key;
  20. }
  21. if (isCryptoKey(key)) {
  22. checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');
  23. return KeyObject.from(key).export();
  24. }
  25. throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
  26. }
  27. export const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {
  28. checkP2s(p2s);
  29. const salt = concatSalt(alg, p2s);
  30. const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
  31. const password = getPassword(key, alg);
  32. const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
  33. const encryptedKey = await wrap(alg.slice(-6), derivedKey, cek);
  34. return { encryptedKey, p2c, p2s: base64url(p2s) };
  35. };
  36. export const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {
  37. checkP2s(p2s);
  38. const salt = concatSalt(alg, p2s);
  39. const keylen = parseInt(alg.slice(13, 16), 10) >> 3;
  40. const password = getPassword(key, alg);
  41. const derivedKey = await pbkdf2(password, salt, p2c, keylen, `sha${alg.slice(8, 11)}`);
  42. return unwrap(alg.slice(-6), derivedKey, encryptedKey);
  43. };