import.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { decode as decodeBase64URL } from '../util/base64url.js';
  2. import { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';
  3. import { jwkToKey } from '../lib/jwk_to_key.js';
  4. import { JOSENotSupported } from '../util/errors.js';
  5. import { isObject } from '../lib/type_checks.js';
  6. export async function importSPKI(spki, alg, options) {
  7. if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
  8. throw new TypeError('"spki" must be SPKI formatted string');
  9. }
  10. return fromSPKI(spki, alg, options);
  11. }
  12. export async function importX509(x509, alg, options) {
  13. if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {
  14. throw new TypeError('"x509" must be X.509 formatted string');
  15. }
  16. return fromX509(x509, alg, options);
  17. }
  18. export async function importPKCS8(pkcs8, alg, options) {
  19. if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {
  20. throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
  21. }
  22. return fromPKCS8(pkcs8, alg, options);
  23. }
  24. export async function importJWK(jwk, alg, options) {
  25. if (!isObject(jwk)) {
  26. throw new TypeError('JWK must be an object');
  27. }
  28. let ext;
  29. alg ??= jwk.alg;
  30. ext ??= options?.extractable ?? jwk.ext;
  31. switch (jwk.kty) {
  32. case 'oct':
  33. if (typeof jwk.k !== 'string' || !jwk.k) {
  34. throw new TypeError('missing "k" (Key Value) Parameter value');
  35. }
  36. return decodeBase64URL(jwk.k);
  37. case 'RSA':
  38. if ('oth' in jwk && jwk.oth !== undefined) {
  39. throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
  40. }
  41. return jwkToKey({ ...jwk, alg, ext });
  42. case 'AKP': {
  43. if (typeof jwk.alg !== 'string' || !jwk.alg) {
  44. throw new TypeError('missing "alg" (Algorithm) Parameter value');
  45. }
  46. if (alg !== undefined && alg !== jwk.alg) {
  47. throw new TypeError('JWK alg and alg option value mismatch');
  48. }
  49. return jwkToKey({ ...jwk, ext });
  50. }
  51. case 'EC':
  52. case 'OKP':
  53. return jwkToKey({ ...jwk, alg, ext });
  54. default:
  55. throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
  56. }
  57. }