rsaes.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import subtleAlgorithm from './subtle_rsaes.js';
  2. import bogusWebCrypto from './bogus.js';
  3. import crypto, { isCryptoKey } from './webcrypto.js';
  4. import { checkEncCryptoKey } from '../lib/crypto_key.js';
  5. import checkKeyLength from './check_key_length.js';
  6. import invalidKeyInput from '../lib/invalid_key_input.js';
  7. import { types } from './is_key_like.js';
  8. export const encrypt = async (alg, key, cek) => {
  9. if (!isCryptoKey(key)) {
  10. throw new TypeError(invalidKeyInput(key, ...types));
  11. }
  12. checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey');
  13. checkKeyLength(alg, key);
  14. if (key.usages.includes('encrypt')) {
  15. return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));
  16. }
  17. if (key.usages.includes('wrapKey')) {
  18. const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);
  19. return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)));
  20. }
  21. throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation');
  22. };
  23. export const decrypt = async (alg, key, encryptedKey) => {
  24. if (!isCryptoKey(key)) {
  25. throw new TypeError(invalidKeyInput(key, ...types));
  26. }
  27. checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey');
  28. checkKeyLength(alg, key);
  29. if (key.usages.includes('decrypt')) {
  30. return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));
  31. }
  32. if (key.usages.includes('unwrapKey')) {
  33. const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto);
  34. return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
  35. }
  36. throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation');
  37. };