Skip to content

Commit 801ed71

Browse files
committed
Add constants for ASN tags and sizes to improve readability
1 parent c184d07 commit 801ed71

1 file changed

Lines changed: 32 additions & 13 deletions

File tree

src/Key/PublicKey.php

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,25 @@
1919
*/
2020
class PublicKey extends AsymmetricKey
2121
{
22+
/** @var int */
23+
public const ASN1_TYPE_INTEGER = 0x02; // 2
24+
25+
/** @var int */
26+
public const ASN1_TYPE_BIT_STRING = 0x03; // 3
27+
28+
/** @var int */
29+
public const ASN1_TYPE_SEQUENCE = 0x30; // 16
30+
31+
/** @var int */
32+
public const ASN1_SIZE_128 = 0x80; // 128
33+
34+
/** @var int */
35+
public const ASN1_SIZE_256 = 0x0100; // 256
36+
37+
/** @var int */
38+
public const ASN1_SIZE_65535 = 0x010000; // 65535
39+
40+
2241
/**
2342
* Create a new public key from the PEM-encoded key material.
2443
*
@@ -56,24 +75,24 @@ public static function fromFile(string $file): PublicKey
5675
protected static function makeASN1Segment(int $type, string $string): ?string
5776
{
5877
switch ($type) {
59-
case 0x02:
60-
if (ord($string) > 0x7f) {
78+
case self::ASN1_TYPE_INTEGER:
79+
if (ord($string) > self::ASN1_SIZE_128 - 1) {
6180
$string = chr(0) . $string;
6281
}
6382
break;
64-
case 0x03:
83+
case self::ASN1_TYPE_BIT_STRING:
6584
$string = chr(0) . $string;
6685
break;
6786
}
6887

6988
$length = strlen($string);
7089

71-
if ($length < 128) {
90+
if ($length < self::ASN1_SIZE_128) {
7291
$output = sprintf("%c%c%s", $type, $length, $string);
73-
} elseif ($length < 0x0100) {
74-
$output = sprintf("%c%c%c%s", $type, 0x81, $length, $string);
75-
} elseif ($length < 0x010000) {
76-
$output = sprintf("%c%c%c%c%s", $type, 0x82, $length / 0x0100, $length % 0x0100, $string);
92+
} elseif ($length < self::ASN1_SIZE_256) {
93+
$output = sprintf("%c%c%c%s", $type, self::ASN1_SIZE_128 + 1, $length, $string);
94+
} elseif ($length < self::ASN1_SIZE_65535) {
95+
$output = sprintf("%c%c%c%c%s", $type, self::ASN1_SIZE_128 +2, $length / 0x0100, $length % 0x0100, $string);
7796
} else {
7897
$output = null;
7998
}
@@ -96,14 +115,14 @@ public static function fromDetails(string $modulus, string $exponent): PublicKey
96115
chunk_split(
97116
base64_encode(
98117
self::makeASN1Segment(
99-
0x30,
118+
self::ASN1_TYPE_SEQUENCE,
100119
pack("H*", "300D06092A864886F70D0101010500") . // RSA alg id
101120
self::makeASN1Segment( // bitstring
102-
0x03,
121+
self::ASN1_TYPE_BIT_STRING,
103122
self::makeASN1Segment( // sequence
104-
0x30,
105-
self::makeASN1Segment(0x02, $modulus) .
106-
self::makeASN1Segment(0x02, $exponent)
123+
self::ASN1_TYPE_SEQUENCE,
124+
self::makeASN1Segment(self::ASN1_TYPE_INTEGER, $modulus)
125+
. self::makeASN1Segment(self::ASN1_TYPE_INTEGER, $exponent)
107126
)
108127
)
109128
)

0 commit comments

Comments
 (0)