pem.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.toDER = toDER;
  4. exports.fromDER = fromDER;
  5. /*
  6. Copyright 2023 The Sigstore Authors.
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. */
  17. const PEM_HEADER = /-----BEGIN (.*)-----/;
  18. const PEM_FOOTER = /-----END (.*)-----/;
  19. function toDER(certificate) {
  20. let der = '';
  21. certificate.split('\n').forEach((line) => {
  22. if (line.match(PEM_HEADER) || line.match(PEM_FOOTER)) {
  23. return;
  24. }
  25. der += line;
  26. });
  27. return Buffer.from(der, 'base64');
  28. }
  29. // Translates a DER-encoded buffer into a PEM-encoded string. Standard PEM
  30. // encoding dictates that each certificate should have a trailing newline after
  31. // the footer.
  32. function fromDER(certificate, type = 'CERTIFICATE') {
  33. // Base64-encode the certificate.
  34. const der = certificate.toString('base64');
  35. // Split the certificate into lines of 64 characters.
  36. const lines = der.match(/.{1,64}/g) || '';
  37. return [`-----BEGIN ${type}-----`, ...lines, `-----END ${type}-----`]
  38. .join('\n')
  39. .concat('\n');
  40. }