MediaWiki
master
Toggle main menu visibility
MWCryptHash.php
Go to the documentation of this file.
1
<?php
6
7
namespace
Wikimedia
;
8
9
use DomainException;
10
use InvalidArgumentException;
11
18
class
MWCryptHash
{
22
protected
static
?
string
$algo
=
null
;
23
27
protected
static
int
$hashLength
;
28
33
public
static
function
hashAlgo
() {
34
$algorithm = self::$algo;
35
if
( $algorithm !==
null
) {
36
return
$algorithm;
37
}
38
39
$algos = hash_hmac_algos();
40
$preference = [
'whirlpool'
,
'sha256'
];
41
42
foreach
( $preference as $algorithm ) {
43
if
( in_array( $algorithm, $algos,
true
) ) {
44
self::$algo = $algorithm;
45
return
$algorithm;
46
}
47
}
48
49
throw
new
DomainException(
'Could not find an acceptable hashing function.'
);
50
}
51
60
public
static
function
hashLength
( $raw =
true
) {
61
self::$hashLength ??= strlen( self::hash(
''
,
true
) );
62
// Optimisation: Skip computing the length of non-raw hashes.
63
// The algos in hashAlgo() all produce a digest that is a multiple
64
// of 8 bits, where hex is always twice the length of binary byte length.
65
return
$raw ? self::$hashLength : self::$hashLength * 2;
66
}
67
76
public
static
function
hash
( $data, $raw =
true
) {
77
return
hash
( self::hashAlgo(), $data, $raw );
78
}
79
89
public
static
function
hmac
( $data, $key, $raw =
true
) {
90
if
( !is_string( $key ) ) {
91
// hash_hmac tolerates non-string (would return null with warning)
92
throw
new
InvalidArgumentException(
'Invalid key type: '
. get_debug_type( $key ) );
93
}
94
return
hash_hmac( self::hashAlgo(), $data, $key, $raw );
95
}
96
97
}
98
100
class_alias( MWCryptHash::class,
'MWCryptHash'
);
Wikimedia\MWCryptHash
Utility functions for generating hashes.
Definition
MWCryptHash.php:18
Wikimedia\MWCryptHash\hmac
static hmac( $data, $key, $raw=true)
Generate a keyed cryptographic hash value (HMAC) for a string, making use of the best hash algorithm ...
Definition
MWCryptHash.php:89
Wikimedia\MWCryptHash\hashAlgo
static hashAlgo()
Decide on the best acceptable hash algorithm we have available for hash().
Definition
MWCryptHash.php:33
Wikimedia\MWCryptHash\hash
static hash( $data, $raw=true)
Generate a cryptographic hash value (message digest) for a string, making use of the best hash algori...
Definition
MWCryptHash.php:76
Wikimedia\MWCryptHash\$hashLength
static int $hashLength
The number of bytes outputted by the hash algorithm.
Definition
MWCryptHash.php:27
Wikimedia\MWCryptHash\hashLength
static hashLength( $raw=true)
Return the byte-length output of the hash algorithm we are using in self\hash and self\hmac.
Definition
MWCryptHash.php:60
Wikimedia\MWCryptHash\$algo
static string $algo
The hash algorithm being used.
Definition
MWCryptHash.php:22
Wikimedia
includes
libs
MWCryptHash.php
Generated on
for MediaWiki by
1.18.0