MediaWiki master
MWCryptHash.php
Go to the documentation of this file.
1<?php
6
7namespace Wikimedia;
8
9use DomainException;
10use InvalidArgumentException;
11
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
100class_alias( MWCryptHash::class, 'MWCryptHash' );
Utility functions for generating hashes.
static hmac( $data, $key, $raw=true)
Generate a keyed cryptographic hash value (HMAC) for a string, making use of the best hash algorithm ...
static hashAlgo()
Decide on the best acceptable hash algorithm we have available for hash().
static hash( $data, $raw=true)
Generate a cryptographic hash value (message digest) for a string, making use of the best hash algori...
static int $hashLength
The number of bytes outputted by the hash algorithm.
static hashLength( $raw=true)
Return the byte-length output of the hash algorithm we are using in self\hash and self\hmac.
static string $algo
The hash algorithm being used.