thumbprint.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import digest from '../runtime/digest.js';
  2. import { encode as base64url } from '../runtime/base64url.js';
  3. import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
  4. import { encoder } from '../lib/buffer_utils.js';
  5. import isObject from '../lib/is_object.js';
  6. const check = (value, description) => {
  7. if (typeof value !== 'string' || !value) {
  8. throw new JWKInvalid(`${description} missing or invalid`);
  9. }
  10. };
  11. export async function calculateJwkThumbprint(jwk, digestAlgorithm) {
  12. if (!isObject(jwk)) {
  13. throw new TypeError('JWK must be an object');
  14. }
  15. digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
  16. if (digestAlgorithm !== 'sha256' &&
  17. digestAlgorithm !== 'sha384' &&
  18. digestAlgorithm !== 'sha512') {
  19. throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
  20. }
  21. let components;
  22. switch (jwk.kty) {
  23. case 'EC':
  24. check(jwk.crv, '"crv" (Curve) Parameter');
  25. check(jwk.x, '"x" (X Coordinate) Parameter');
  26. check(jwk.y, '"y" (Y Coordinate) Parameter');
  27. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
  28. break;
  29. case 'OKP':
  30. check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
  31. check(jwk.x, '"x" (Public Key) Parameter');
  32. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
  33. break;
  34. case 'RSA':
  35. check(jwk.e, '"e" (Exponent) Parameter');
  36. check(jwk.n, '"n" (Modulus) Parameter');
  37. components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
  38. break;
  39. case 'oct':
  40. check(jwk.k, '"k" (Key Value) Parameter');
  41. components = { k: jwk.k, kty: jwk.kty };
  42. break;
  43. default:
  44. throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
  45. }
  46. const data = encoder.encode(JSON.stringify(components));
  47. return base64url(await digest(digestAlgorithm, data));
  48. }
  49. export async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
  50. digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
  51. const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
  52. return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
  53. }