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