key_to_jwk.js 943 B

12345678910111213141516171819202122232425262728293031
  1. import { invalidKeyInput } from './invalid_key_input.js';
  2. import { encode as b64u } from '../util/base64url.js';
  3. import { isCryptoKey, isKeyObject } from './is_key_like.js';
  4. export async function keyToJWK(key) {
  5. if (isKeyObject(key)) {
  6. if (key.type === 'secret') {
  7. key = key.export();
  8. }
  9. else {
  10. return key.export({ format: 'jwk' });
  11. }
  12. }
  13. if (key instanceof Uint8Array) {
  14. return {
  15. kty: 'oct',
  16. k: b64u(key),
  17. };
  18. }
  19. if (!isCryptoKey(key)) {
  20. throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'Uint8Array'));
  21. }
  22. if (!key.extractable) {
  23. throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');
  24. }
  25. const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);
  26. if (jwk.kty === 'AKP') {
  27. ;
  28. jwk.alg = alg;
  29. }
  30. return jwk;
  31. }