key_to_jwk.js 733 B

123456789101112131415161718192021
  1. import crypto, { isCryptoKey } from './webcrypto.js';
  2. import invalidKeyInput from '../lib/invalid_key_input.js';
  3. import { encode as base64url } from './base64url.js';
  4. import { types } from './is_key_like.js';
  5. const keyToJWK = async (key) => {
  6. if (key instanceof Uint8Array) {
  7. return {
  8. kty: 'oct',
  9. k: base64url(key),
  10. };
  11. }
  12. if (!isCryptoKey(key)) {
  13. throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));
  14. }
  15. if (!key.extractable) {
  16. throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
  17. }
  18. const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);
  19. return jwk;
  20. };
  21. export default keyToJWK;