| 1 |
"use strict"; |
| 2 |
/* |
| 3 |
Copyright 2023 The Sigstore Authors. |
| 4 |
|
| 5 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
you may not use this file except in compliance with the License. |
| 7 |
You may obtain a copy of the License at |
| 8 |
|
| 9 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
|
| 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 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 18 |
exports.decodeLength = decodeLength; |
| 19 |
exports.encodeLength = encodeLength; |
| 20 |
const error_1 = require("./error"); |
| 21 |
// Decodes the length of a DER-encoded ANS.1 element from the supplied stream. |
| 22 |
// https://learn.microsoft.com/en-us/windows/win32/seccertenroll/about-encoded-length-and-value-bytes |
| 23 |
function decodeLength(stream) { |
| 24 |
const buf = stream.getUint8(); |
| 25 |
// If the most significant bit is UNSET the length is just the value of the |
| 26 |
// byte. |
| 27 |
if ((buf & 0x80) === 0x00) { |
| 28 |
return buf; |
| 29 |
} |
| 30 |
// Otherwise, the lower 7 bits of the first byte indicate the number of bytes |
| 31 |
// that follow to encode the length. |
| 32 |
const byteCount = buf & 0x7f; |
| 33 |
// Ensure the encoded length can safely fit in a JS number. |
| 34 |
if (byteCount > 6) { |
| 35 |
throw new error_1.ASN1ParseError('length exceeds 6 byte limit'); |
| 36 |
} |
| 37 |
// Iterate over the bytes that encode the length. |
| 38 |
let len = 0; |
| 39 |
for (let i = 0; i < byteCount; i++) { |
| 40 |
len = len * 256 + stream.getUint8(); |
| 41 |
} |
| 42 |
// This is a valid ASN.1 length encoding, but we don't support it. |
| 43 |
if (len === 0) { |
| 44 |
throw new error_1.ASN1ParseError('indefinite length encoding not supported'); |
| 45 |
} |
| 46 |
return len; |
| 47 |
} |
| 48 |
// Translates the supplied value to a DER-encoded length. |
| 49 |
function encodeLength(len) { |
| 50 |
if (len < 128) { |
| 51 |
return Buffer.from([len]); |
| 52 |
} |
| 53 |
// Bitwise operations on large numbers are not supported in JS, so we need to |
| 54 |
// use BigInts. |
| 55 |
let val = BigInt(len); |
| 56 |
const bytes = []; |
| 57 |
while (val > 0n) { |
| 58 |
bytes.unshift(Number(val & 255n)); |
| 59 |
val = val >> 8n; |
| 60 |
} |
| 61 |
return Buffer.from([0x80 | bytes.length, ...bytes]); |
| 62 |
} |