codekingpro/portable-devtools
114k
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.createPublicKey = createPublicKey;
7exports.digest = digest;
8exports.verify = verify;
9exports.bufferEqual = bufferEqual;
10/*
11Copyright 2023 The Sigstore Authors.
12
13Licensed under the Apache License, Version 2.0 (the "License");
14you may not use this file except in compliance with the License.
15You may obtain a copy of the License at
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
19Unless required by applicable law or agreed to in writing, software
20distributed under the License is distributed on an "AS IS" BASIS,
21WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22See the License for the specific language governing permissions and
23limitations under the License.
24*/
25const crypto_1 = __importDefault(require("crypto"));
26function createPublicKey(key, type = 'spki') {
27 if (typeof key === 'string') {
28 if (key.startsWith('-----')) {
29 return crypto_1.default.createPublicKey(key);
30 }
31 else {
32 return crypto_1.default.createPublicKey({
33 key: Buffer.from(key, 'base64'),
34 format: 'der',
35 type: type,
36 });
37 }
38 }
39 else {
40 return crypto_1.default.createPublicKey({ key, format: 'der', type: type });
41 }
42}
43function digest(algorithm, ...data) {
44 const hash = crypto_1.default.createHash(algorithm);
45 for (const d of data) {
46 hash.update(d);
47 }
48 return hash.digest();
49}
50function verify(data, key, signature, algorithm) {
51 // The try/catch is to work around an issue in Node 14.x where verify throws
52 // an error in some scenarios if the signature is invalid.
53 try {
54 return crypto_1.default.verify(algorithm, data, key, signature);
55 }
56 catch (e) {
57 /* istanbul ignore next */
58 return false;
59 }
60}
61function bufferEqual(a, b) {
62 try {
63 return crypto_1.default.timingSafeEqual(a, b);
64 }
65 catch {
66 /* istanbul ignore next */
67 return false;
68 }
69}
70 