Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Encryption/Algorithm/KeyEncryption/Util/ConcatKDF.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\Base64UrlSafe;
9 use const STR_PAD_LEFT;
10
11 /**
12 * @internal
13 *
14 * @see https://tools.ietf.org/html/rfc7518#section-4.6.2
15 */
16 final class ConcatKDF
17 {
18 /**
19 * Key Derivation Function.
20 *
21 * @param string $Z Shared secret
22 * @param string $algorithm Encryption algorithm
23 * @param int $encryption_key_size Size of the encryption key
24 * @param string $apu Agreement PartyUInfo (information about the producer)
25 * @param string $apv Agreement PartyVInfo (information about the recipient)
26 */
27 public static function generate(
28 string $Z,
29 string $algorithm,
30 int $encryption_key_size,
31 string $apu = '',
32 string $apv = ''
33 ): string {
34 $apu = ! self::isEmpty($apu) ? Base64UrlSafe::decodeNoPadding($apu) : '';
35 $apv = ! self::isEmpty($apv) ? Base64UrlSafe::decodeNoPadding($apv) : '';
36 $encryption_segments = [
37 self::toInt32Bits(1), // Round number 1
38 $Z, // Z (shared secret)
39 self::toInt32Bits(mb_strlen($algorithm, '8bit')) . $algorithm, // Size of algorithm's name and algorithm
40 self::toInt32Bits(mb_strlen($apu, '8bit')) . $apu, // PartyUInfo
41 self::toInt32Bits(mb_strlen($apv, '8bit')) . $apv, // PartyVInfo
42 self::toInt32Bits($encryption_key_size), // SuppPubInfo (the encryption key size)
43 '', // SuppPrivInfo
44 ];
45
46 $input = implode('', $encryption_segments);
47 $hash = hash('sha256', $input, true);
48
49 return mb_substr($hash, 0, $encryption_key_size / 8, '8bit');
50 }
51
52 /**
53 * Convert an integer into a 32 bits string.
54 *
55 * @param int $value Integer to convert
56 */
57 private static function toInt32Bits(int $value): string
58 {
59 $result = hex2bin(str_pad(dechex($value), 8, '0', STR_PAD_LEFT));
60 if ($result === false) {
61 throw new InvalidArgumentException('Invalid result');
62 }
63
64 return $result;
65 }
66
67 private static function isEmpty(?string $value): bool
68 {
69 return $value === null || $value === '';
70 }
71 }