import.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { decode as decodeBase64URL } from '../runtime/base64url.js';
  2. import { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js';
  3. import asKeyObject from '../runtime/jwk_to_key.js';
  4. import { JOSENotSupported } from '../util/errors.js';
  5. import isObject from '../lib/is_object.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, octAsKeyObject) {
  25. var _a;
  26. if (!isObject(jwk)) {
  27. throw new TypeError('JWK must be an object');
  28. }
  29. alg || (alg = jwk.alg);
  30. switch (jwk.kty) {
  31. case 'oct':
  32. if (typeof jwk.k !== 'string' || !jwk.k) {
  33. throw new TypeError('missing "k" (Key Value) Parameter value');
  34. }
  35. octAsKeyObject !== null && octAsKeyObject !== void 0 ? octAsKeyObject : (octAsKeyObject = jwk.ext !== true);
  36. if (octAsKeyObject) {
  37. return asKeyObject({ ...jwk, alg, ext: (_a = jwk.ext) !== null && _a !== void 0 ? _a : false });
  38. }
  39. return decodeBase64URL(jwk.k);
  40. case 'RSA':
  41. if (jwk.oth !== undefined) {
  42. throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
  43. }
  44. case 'EC':
  45. case 'OKP':
  46. return asKeyObject({ ...jwk, alg });
  47. default:
  48. throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
  49. }
  50. }