| 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 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
final class ConcatKDF |
| 17 |
{ |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 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), |
| 38 |
$Z, |
| 39 |
self::toInt32Bits(mb_strlen($algorithm, '8bit')) . $algorithm, |
| 40 |
self::toInt32Bits(mb_strlen($apu, '8bit')) . $apu, |
| 41 |
self::toInt32Bits(mb_strlen($apv, '8bit')) . $apv, |
| 42 |
self::toInt32Bits($encryption_key_size), |
| 43 |
'', |
| 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 |
|
| 54 |
|
| 55 |
|
| 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 |
} |