Debian Codegraph @

lib/3rdParty/composer/spomky-labs/pki-framework/src/ASN1/Component/Length.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SpomkyLabs\Pki\ASN1\Component;
6
7 use Brick\Math\BigInteger;
8 use function count;
9 use DomainException;
10 use LogicException;
11 use function mb_strlen;
12 use function ord;
13 use SpomkyLabs\Pki\ASN1\Exception\DecodeException;
14 use SpomkyLabs\Pki\ASN1\Feature\Encodable;
15 use SpomkyLabs\Pki\ASN1\Util\BigInt;
16 use function sprintf;
17
18 /**
19 * Class to represent BER/DER length octets.
20 */
21 final class Length implements Encodable
22 {
23 /**
24 * Length.
25 */
26 private readonly BigInt $_length;
27
28 /**
29 * @param BigInteger|int $length Length
30 * @param bool $_indefinite Whether length is indefinite
31 */
32 private function __construct(
33 BigInteger|int $length,
34 private readonly bool $_indefinite = false
35 ) {
36 $this->_length = BigInt::create($length);
37 }
38
39 public static function create(BigInteger|int $length, bool $_indefinite = false): self
40 {
41 return new self($length, $_indefinite);
42 }
43
44 /**
45 * Decode length component from DER data.
46 *
47 * @param string $data DER encoded data
48 * @param null|int $offset Reference to the variable that contains offset
49 * into the data where to start parsing.
50 * Variable is updated to the offset next to the
51 * parsed length component. If null, start from offset 0.
52 */
53 public static function fromDER(string $data, ?int &$offset = null): self
54 {
55 $idx = $offset ?? 0;
56 $datalen = mb_strlen($data, '8bit');
57 if ($idx >= $datalen) {
58 throw new DecodeException('Unexpected end of data while decoding length.');
59 }
60 $indefinite = false;
61 $byte = ord($data[$idx++]);
62 // bits 7 to 1
63 $length = (0x7f & $byte);
64 // long form
65 if ((0x80 & $byte) !== 0) {
66 if ($length === 0) {
67 $indefinite = true;
68 } else {
69 if ($idx + $length > $datalen) {
70 throw new DecodeException('Unexpected end of data while decoding long form length.');
71 }
72 $length = self::decodeLongFormLength($length, $data, $idx);
73 }
74 }
75 if (isset($offset)) {
76 $offset = $idx;
77 }
78 return self::create($length, $indefinite);
79 }
80
81 /**
82 * Decode length from DER.
83 *
84 * Throws an exception if length doesn't match with expected or if data doesn't contain enough bytes.
85 *
86 * Requirement of definite length is relaxed contrary to the specification (sect. 10.1).
87 *
88 * @param string $data DER data
89 * @param int $offset Reference to the offset variable
90 * @param null|int $expected Expected length, null to bypass checking
91 * @see self::fromDER
92 */
93 public static function expectFromDER(string $data, int &$offset, ?int $expected = null): self
94 {
95 $idx = $offset;
96 $length = self::fromDER($data, $idx);
97 // if certain length was expected
98 if (isset($expected)) {
99 if ($length->isIndefinite()) {
100 throw new DecodeException(sprintf('Expected length %d, got indefinite.', $expected));
101 }
102 if ($expected !== $length->intLength()) {
103 throw new DecodeException(sprintf('Expected length %d, got %d.', $expected, $length->intLength()));
104 }
105 }
106 // check that enough data is available
107 if (! $length->isIndefinite()
108 && mb_strlen($data, '8bit') < $idx + $length->intLength()) {
109 throw new DecodeException(
110 sprintf(
111 'Length %d overflows data, %d bytes left.',
112 $length->intLength(),
113 mb_strlen($data, '8bit') - $idx
114 )
115 );
116 }
117 $offset = $idx;
118 return $length;
119 }
120
121 public function toDER(): string
122 {
123 $bytes = [];
124 if ($this->_indefinite) {
125 $bytes[] = 0x80;
126 } else {
127 $num = $this->_length->getValue();
128 // long form
129 if ($num->isGreaterThan(127)) {
130 $octets = [];
131 for (; $num->isGreaterThan(0); $num = $num->shiftedRight(8)) {
132 $octets[] = BigInteger::of(0xff)->and($num)->toInt();
133 }
134 $count = count($octets);
135 // first octet must not be 0xff
136 if ($count >= 127) {
137 throw new DomainException('Too many length octets.');
138 }
139 $bytes[] = 0x80 | $count;
140 foreach (array_reverse($octets) as $octet) {
141 $bytes[] = $octet;
142 }
143 } // short form
144 else {
145 $bytes[] = $num->toInt();
146 }
147 }
148 return pack('C*', ...$bytes);
149 }
150
151 /**
152 * Get the length.
153 *
154 * @return string Length as an integer string
155 */
156 public function length(): string
157 {
158 if ($this->_indefinite) {
159 throw new LogicException('Length is indefinite.');
160 }
161 return $this->_length->base10();
162 }
163
164 /**
165 * Get the length as an integer.
166 */
167 public function intLength(): int
168 {
169 if ($this->_indefinite) {
170 throw new LogicException('Length is indefinite.');
171 }
172 return $this->_length->toInt();
173 }
174
175 /**
176 * Whether length is indefinite.
177 */
178 public function isIndefinite(): bool
179 {
180 return $this->_indefinite;
181 }
182
183 /**
184 * Decode long form length.
185 *
186 * @param int $length Number of octets
187 * @param string $data Data
188 * @param int $offset reference to the variable containing offset to the data
189 */
190 private static function decodeLongFormLength(int $length, string $data, int &$offset): BigInteger
191 {
192 // first octet must not be 0xff (spec 8.1.3.5c)
193 if ($length === 127) {
194 throw new DecodeException('Invalid number of length octets.');
195 }
196 $num = BigInteger::of(0);
197 while (--$length >= 0) {
198 $byte = ord($data[$offset++]);
199 $num = $num->shiftedLeft(8)
200 ->or($byte);
201 }
202
203 return $num;
204 }
205 }