MediaWiki master
MWCryptHash.php
Go to the documentation of this file.
1<?php
17 protected static ?string $algo = null;
18
22 protected static int $hashLength;
23
28 public static function hashAlgo() {
29 $algorithm = self::$algo;
30 if ( $algorithm !== null ) {
31 return $algorithm;
32 }
33
34 $algos = hash_hmac_algos();
35 $preference = [ 'whirlpool', 'sha256' ];
36
37 foreach ( $preference as $algorithm ) {
38 if ( in_array( $algorithm, $algos, true ) ) {
39 self::$algo = $algorithm;
40 return $algorithm;
41 }
42 }
43
44 throw new DomainException( 'Could not find an acceptable hashing function.' );
45 }
46
55 public static function hashLength( $raw = true ) {
56 self::$hashLength ??= strlen( self::hash( '', true ) );
57 // Optimisation: Skip computing the length of non-raw hashes.
58 // The algos in hashAlgo() all produce a digest that is a multiple
59 // of 8 bits, where hex is always twice the length of binary byte length.
60 return $raw ? self::$hashLength : self::$hashLength * 2;
61 }
62
71 public static function hash( $data, $raw = true ) {
72 return hash( self::hashAlgo(), $data, $raw );
73 }
74
84 public static function hmac( $data, $key, $raw = true ) {
85 if ( !is_string( $key ) ) {
86 // hash_hmac tolerates non-string (would return null with warning)
87 throw new InvalidArgumentException( 'Invalid key type: ' . get_debug_type( $key ) );
88 }
89 return hash_hmac( self::hashAlgo(), $data, $key, $raw );
90 }
91
92}
Utility functions for generating hashes.
static hashAlgo()
Decide on the best acceptable hash algorithm we have available for hash()
static hashLength( $raw=true)
Return the byte-length output of the hash algorithm we are using in self::hash and self::hmac.
static int $hashLength
The number of bytes outputted by the hash algorithm.
static string $algo
The hash algorithm being used.
static hmac( $data, $key, $raw=true)
Generate a keyed cryptographic hash value (HMAC) for a string, making use of the best hash algorithm ...
static hash( $data, $raw=true)
Generate a cryptographic hash value (message digest) for a string, making use of the best hash algori...