Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Encryption/Algorithm/KeyEncryption/Util/RSACrypt.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Encryption\Algorithm\KeyEncryption\Util;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\Util\BigInteger;
9 use Jose\Component\Core\Util\Hash;
10 use Jose\Component\Core\Util\RSAKey;
11 use LogicException;
12 use RuntimeException;
13 use function chr;
14 use function count;
15 use function ord;
16 use const STR_PAD_LEFT;
17
18 /**
19 * @internal
20 */
21 final class RSACrypt
22 {
23 /**
24 * Optimal Asymmetric Encryption Padding (OAEP).
25 */
26 public const ENCRYPTION_OAEP = 1;
27
28 /**
29 * Use PKCS#1 padding.
30 */
31 public const ENCRYPTION_PKCS1 = 2;
32
33 public static function encrypt(RSAKey $key, string $data, int $mode, ?string $hash = null): string
34 {
35 switch ($mode) {
36 case self::ENCRYPTION_OAEP:
37 if ($hash === null) {
38 throw new LogicException('Hash shall be defined for RSA OAEP cyphering');
39 }
40
41 return self::encryptWithRSAOAEP($key, $data, $hash);
42 case self::ENCRYPTION_PKCS1:
43 return self::encryptWithRSA15($key, $data);
44 default:
45 throw new InvalidArgumentException('Unsupported mode.');
46 }
47 }
48
49 public static function decrypt(
50 RSAKey $key,
51 string $plaintext,
52 int $mode,
53 ?string $hash = null,
54 ?int $expectedKeyLength = null
55 ): string {
56 switch ($mode) {
57 case self::ENCRYPTION_OAEP:
58 if ($hash === null) {
59 throw new LogicException('Hash shall be defined for RSA OAEP cyphering');
60 }
61
62 return self::decryptWithRSAOAEP($key, $plaintext, $hash);
63 case self::ENCRYPTION_PKCS1:
64 return self::decryptWithRSA15($key, $plaintext, $expectedKeyLength);
65 default:
66 throw new InvalidArgumentException('Unsupported mode.');
67 }
68 }
69
70 public static function encryptWithRSA15(RSAKey $key, string $data): string
71 {
72 $mLen = mb_strlen($data, '8bit');
73 if ($mLen > $key->getModulusLength() - 11) {
74 throw new InvalidArgumentException('Message too long');
75 }
76
77 $psLen = $key->getModulusLength() - $mLen - 3;
78 $ps = '';
79 while (mb_strlen($ps, '8bit') !== $psLen) {
80 $temp = random_bytes($psLen - mb_strlen($ps, '8bit'));
81 $temp = str_replace("\x00", '', $temp);
82 $ps .= $temp;
83 }
84 $type = 2;
85 $data = chr(0) . chr($type) . $ps . chr(0) . $data;
86
87 $binaryData = BigInteger::createFromBinaryString($data);
88 $c = self::getRSAEP($key, $binaryData);
89
90 return self::convertIntegerToOctetString($c, $key->getModulusLength());
91 }
92
93 public static function decryptWithRSA15(RSAKey $key, string $c, ?int $expectedKeyLength = null): string
94 {
95 if (mb_strlen($c, '8bit') !== $key->getModulusLength()) {
96 throw new InvalidArgumentException('Unable to decrypt');
97 }
98 $c = BigInteger::createFromBinaryString($c);
99 $m = self::getRSADP($key, $c);
100 $em = self::convertIntegerToOctetString($m, $key->getModulusLength());
101
102 if ($expectedKeyLength === null) {
103 if (ord($em[0]) !== 0 || ord($em[1]) > 2) {
104 throw new InvalidArgumentException('Unable to decrypt');
105 }
106 $ps = mb_substr($em, 2, (int) mb_strpos($em, chr(0), 2, '8bit') - 2, '8bit');
107 $m = mb_substr($em, mb_strlen($ps, '8bit') + 3, null, '8bit');
108 if (mb_strlen($ps, '8bit') < 8) {
109 throw new InvalidArgumentException('Unable to decrypt');
110 }
111
112 return $m;
113 }
114
115 return self::extractRSA15KeyOrRandom($em, $expectedKeyLength);
116 }
117
118 private static function extractRSA15KeyOrRandom(string $em, int $expectedKeyLength): string
119 {
120 $k = mb_strlen($em, '8bit');
121 $random = random_bytes($expectedKeyLength);
122
123 if ($k < $expectedKeyLength + 11) {
124 return $random;
125 }
126 $candidate = mb_substr($em, $k - $expectedKeyLength, null, '8bit');
127
128 $valid = self::ctEq(ord($em[0]), 0x00) & self::ctEq(ord($em[1]), 0x02);
129
130 $seenSeparator = 0;
131 $separatorIndex = 0;
132 $psLength = 0;
133 for ($i = 2; $i < $k; ++$i) {
134 $isZero = self::ctEq(ord($em[$i]), 0x00);
135 $firstZero = $isZero & (1 - $seenSeparator);
136 $separatorIndex |= $firstZero * $i;
137 $psLength += (1 - $seenSeparator) & (1 - $isZero);
138 $seenSeparator |= $isZero;
139 }
140
141 $valid &= $seenSeparator;
142 $valid &= self::ctGe($psLength, 8);
143
144 $messageLength = $k - $separatorIndex - 1;
145 $valid &= self::ctEq($messageLength, $expectedKeyLength);
146
147 return self::ctSelect($valid, $candidate, $random);
148 }
149
150 private static function ctEq(int $a, int $b): int
151 {
152 $diff = $a ^ $b;
153
154 return (($diff - 1) >> 63) & 1;
155 }
156
157 private static function ctGe(int $a, int $b): int
158 {
159 return (($b - $a - 1) >> 63) & 1;
160 }
161
162 private static function ctSelect(int $condition, string $a, string $b): string
163 {
164 $mask = str_repeat(chr(($condition * 0xFF) & 0xFF), mb_strlen($a, '8bit'));
165
166 return ($a & $mask) | ($b & ~$mask);
167 }
168
169 /**
170 * Encryption.
171 */
172 public static function encryptWithRSAOAEP(RSAKey $key, string $plaintext, string $hash_algorithm): string
173 {
174 /** @var Hash $hash */
175 $hash = Hash::$hash_algorithm();
176 $length = $key->getModulusLength() - 2 * $hash->getLength() - 2;
177 if ($length <= 0) {
178 throw new RuntimeException();
179 }
180 $splitPlaintext = mb_str_split($plaintext, $length, '8bit');
181 $ciphertext = '';
182 foreach ($splitPlaintext as $m) {
183 $ciphertext .= self::encryptRSAESOAEP($key, $m, $hash);
184 }
185
186 return $ciphertext;
187 }
188
189 /**
190 * Decryption.
191 */
192 public static function decryptWithRSAOAEP(RSAKey $key, string $ciphertext, string $hash_algorithm): string
193 {
194 if ($key->getModulusLength() <= 0) {
195 throw new RuntimeException('Invalid modulus length');
196 }
197 $hash = Hash::$hash_algorithm();
198 $splitCiphertext = mb_str_split($ciphertext, $key->getModulusLength(), '8bit');
199 $splitCiphertext[count($splitCiphertext) - 1] = str_pad(
200 $splitCiphertext[count($splitCiphertext) - 1],
201 $key->getModulusLength(),
202 chr(0),
203 STR_PAD_LEFT
204 );
205 $plaintext = '';
206 foreach ($splitCiphertext as $c) {
207 $temp = self::getRSAESOAEP($key, $c, $hash);
208 $plaintext .= $temp;
209 }
210
211 return $plaintext;
212 }
213
214 private static function convertIntegerToOctetString(BigInteger $x, int $xLen): string
215 {
216 $x = $x->toBytes();
217 if (mb_strlen($x, '8bit') > $xLen) {
218 throw new RuntimeException('Invalid length.');
219 }
220
221 return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
222 }
223
224 /**
225 * Octet-String-to-Integer primitive.
226 */
227 private static function convertOctetStringToInteger(string $x): BigInteger
228 {
229 return BigInteger::createFromBinaryString($x);
230 }
231
232 /**
233 * RSA EP.
234 */
235 private static function getRSAEP(RSAKey $key, BigInteger $m): BigInteger
236 {
237 if ($m->compare(BigInteger::createFromDecimal(0)) < 0 || $m->compare($key->getModulus()) > 0) {
238 throw new RuntimeException();
239 }
240
241 return RSAKey::exponentiate($key, $m);
242 }
243
244 /**
245 * RSA DP.
246 */
247 private static function getRSADP(RSAKey $key, BigInteger $c): BigInteger
248 {
249 if ($c->compare(BigInteger::createFromDecimal(0)) < 0 || $c->compare($key->getModulus()) > 0) {
250 throw new RuntimeException();
251 }
252
253 return RSAKey::exponentiate($key, $c);
254 }
255
256 /**
257 * MGF1.
258 */
259 private static function getMGF1(string $mgfSeed, int $maskLen, Hash $mgfHash): string
260 {
261 $t = '';
262 $count = ceil($maskLen / $mgfHash->getLength());
263 for ($i = 0; $i < $count; ++$i) {
264 $c = pack('N', $i);
265 $t .= $mgfHash->hash($mgfSeed . $c);
266 }
267
268 return mb_substr($t, 0, $maskLen, '8bit');
269 }
270
271 /**
272 * RSAES-OAEP-ENCRYPT.
273 */
274 private static function encryptRSAESOAEP(RSAKey $key, string $m, Hash $hash): string
275 {
276 $mLen = mb_strlen($m, '8bit');
277 $lHash = $hash->hash('');
278 $ps = str_repeat(chr(0), $key->getModulusLength() - $mLen - 2 * $hash->getLength() - 2);
279 $db = $lHash . $ps . chr(1) . $m;
280 $seed = random_bytes($hash->getLength());
281 $dbMask = self::getMGF1($seed, $key->getModulusLength() - $hash->getLength() - 1, $hash/*MGF*/);
282 $maskedDB = $db ^ $dbMask;
283 $seedMask = self::getMGF1($maskedDB, $hash->getLength(), $hash/*MGF*/);
284 $maskedSeed = $seed ^ $seedMask;
285 $em = chr(0) . $maskedSeed . $maskedDB;
286
287 $m = self::convertOctetStringToInteger($em);
288 $c = self::getRSAEP($key, $m);
289
290 return self::convertIntegerToOctetString($c, $key->getModulusLength());
291 }
292
293 /**
294 * RSAES-OAEP-DECRYPT.
295 */
296 private static function getRSAESOAEP(RSAKey $key, string $c, Hash $hash): string
297 {
298 $c = self::convertOctetStringToInteger($c);
299 $m = self::getRSADP($key, $c);
300 $em = self::convertIntegerToOctetString($m, $key->getModulusLength());
301 $lHash = $hash->hash('');
302 $maskedSeed = mb_substr($em, 1, $hash->getLength(), '8bit');
303 $maskedDB = mb_substr($em, $hash->getLength() + 1, null, '8bit');
304 $seedMask = self::getMGF1($maskedDB, $hash->getLength(), $hash/*MGF*/);
305 $seed = $maskedSeed ^ $seedMask;
306 $dbMask = self::getMGF1($seed, $key->getModulusLength() - $hash->getLength() - 1, $hash/*MGF*/);
307 $db = $maskedDB ^ $dbMask;
308 $lHash2 = mb_substr($db, 0, $hash->getLength(), '8bit');
309 $m = mb_substr($db, $hash->getLength(), null, '8bit');
310 if (! hash_equals($lHash, $lHash2)) {
311 throw new RuntimeException();
312 }
313 $m = ltrim($m, chr(0));
314 if (ord($m[0]) !== 1) {
315 throw new RuntimeException();
316 }
317
318 return mb_substr($m, 1, null, '8bit');
319 }
320 }