thumbprint.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { digest } from '../lib/helpers.js';
  2. import { encode as b64u } from '../util/base64url.js';
  3. import { JOSENotSupported, JWKInvalid } from '../util/errors.js';
  4. import { encode } from '../lib/buffer_utils.js';
  5. import { isKeyLike } from '../lib/is_key_like.js';
  6. import { isJWK } from '../lib/type_checks.js';
  7. import { exportJWK } from '../key/export.js';
  8. import { invalidKeyInput } from '../lib/invalid_key_input.js';
  9. const check = (value, description) => {
  10. if (typeof value !== 'string' || !value) {
  11. throw new JWKInvalid(`${description} missing or invalid`);
  12. }
  13. };
  14. export async function calculateJwkThumbprint(key, digestAlgorithm) {
  15. let jwk;
  16. if (isJWK(key)) {
  17. jwk = key;
  18. }
  19. else if (isKeyLike(key)) {
  20. jwk = await exportJWK(key);
  21. }
  22. else {
  23. throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
  24. }
  25. digestAlgorithm ??= 'sha256';
  26. if (digestAlgorithm !== 'sha256' &&
  27. digestAlgorithm !== 'sha384' &&
  28. digestAlgorithm !== 'sha512') {
  29. throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
  30. }
  31. let components;
  32. switch (jwk.kty) {
  33. case 'AKP':
  34. check(jwk.alg, '"alg" (Algorithm) Parameter');
  35. check(jwk.pub, '"pub" (Public key) Parameter');
  36. components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
  37. break;
  38. case 'EC':
  39. check(jwk.crv, '"crv" (Curve) Parameter');
  40. check(jwk.x, '"x" (X Coordinate) Parameter');
  41. check(jwk.y, '"y" (Y Coordinate) Parameter');
  42. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
  43. break;
  44. case 'OKP':
  45. check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
  46. check(jwk.x, '"x" (Public Key) Parameter');
  47. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
  48. break;
  49. case 'RSA':
  50. check(jwk.e, '"e" (Exponent) Parameter');
  51. check(jwk.n, '"n" (Modulus) Parameter');
  52. components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
  53. break;
  54. case 'oct':
  55. check(jwk.k, '"k" (Key Value) Parameter');
  56. components = { k: jwk.k, kty: jwk.kty };
  57. break;
  58. default:
  59. throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
  60. }
  61. const data = encode(JSON.stringify(components));
  62. return b64u(await digest(digestAlgorithm, data));
  63. }
  64. export async function calculateJwkThumbprintUri(key, digestAlgorithm) {
  65. digestAlgorithm ??= 'sha256';
  66. const thumbprint = await calculateJwkThumbprint(key, digestAlgorithm);
  67. return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
  68. }