1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\PKCS5\PRF; |
6
|
|
|
|
7
|
|
|
use Sop\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier; |
8
|
|
|
use Sop\CryptoTypes\AlgorithmIdentifier\Feature\PRFAlgorithmIdentifier; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Base class for pseudorandom functions used in password-based cryptography. |
12
|
|
|
* |
13
|
|
|
* @see https://tools.ietf.org/html/rfc2898#appendix-B.1 |
14
|
|
|
*/ |
15
|
|
|
abstract class PRF |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* Mapping from hash algorithm identifier OID to class name. |
19
|
|
|
* |
20
|
|
|
* @internal |
21
|
|
|
* |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
const MAP_HASH_OID_TO_CLASS = [ |
25
|
|
|
AlgorithmIdentifier::OID_HMAC_WITH_SHA1 => HMACSHA1::class, |
26
|
|
|
AlgorithmIdentifier::OID_HMAC_WITH_SHA224 => HMACSHA224::class, |
27
|
|
|
AlgorithmIdentifier::OID_HMAC_WITH_SHA256 => HMACSHA256::class, |
28
|
|
|
AlgorithmIdentifier::OID_HMAC_WITH_SHA384 => HMACSHA384::class, |
29
|
|
|
AlgorithmIdentifier::OID_HMAC_WITH_SHA512 => HMACSHA512::class, |
30
|
|
|
]; |
31
|
|
|
/** |
32
|
|
|
* Length of the produced output in bytes. |
33
|
|
|
* |
34
|
|
|
* @var int |
35
|
|
|
*/ |
36
|
|
|
protected $_length; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Functor interface. |
40
|
|
|
* |
41
|
|
|
* @param string $arg1 |
42
|
|
|
* @param string $arg2 |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
6 |
|
public function __invoke(string $arg1, string $arg2): string |
47
|
|
|
{ |
48
|
6 |
|
return $this->compute($arg1, $arg2); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Compute pseudorandom value from arguments. |
53
|
|
|
* |
54
|
|
|
* @param string $arg1 First argument |
55
|
|
|
* @param string $arg2 Second argument |
56
|
|
|
* |
57
|
|
|
* @return string Output |
58
|
|
|
*/ |
59
|
|
|
abstract public function compute(string $arg1, string $arg2): string; |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Get output length. |
63
|
|
|
* |
64
|
|
|
* @return int |
65
|
|
|
*/ |
66
|
10 |
|
public function length(): int |
67
|
|
|
{ |
68
|
10 |
|
return $this->_length; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Get PRF by algorithm identifier. |
73
|
|
|
* |
74
|
|
|
* @param PRFAlgorithmIdentifier $algo |
75
|
|
|
* |
76
|
|
|
* @throws \UnexpectedValueException |
77
|
|
|
* |
78
|
|
|
* @return self |
79
|
|
|
*/ |
80
|
8 |
|
public static function fromAlgorithmIdentifier(PRFAlgorithmIdentifier $algo): PRF |
81
|
|
|
{ |
82
|
8 |
|
$oid = $algo->oid(); |
83
|
8 |
|
if (array_key_exists($oid, self::MAP_HASH_OID_TO_CLASS)) { |
84
|
7 |
|
$cls = self::MAP_HASH_OID_TO_CLASS[$oid]; |
85
|
7 |
|
return new $cls(); |
86
|
|
|
} |
87
|
1 |
|
throw new \UnexpectedValueException( |
88
|
1 |
|
'PRF algorithm ' . $algo->oid() . ' not supported.'); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|