MediaWiki master
MWCryptHash.php
Go to the documentation of this file.
1<?php
30 protected static ?string $algo = null;
31
35 protected static int $hashLength;
36
41 public static function hashAlgo() {
42 $algorithm = self::$algo;
43 if ( $algorithm !== null ) {
44 return $algorithm;
45 }
46
47 $algos = hash_hmac_algos();
48 $preference = [ 'whirlpool', 'sha256' ];
49
50 foreach ( $preference as $algorithm ) {
51 if ( in_array( $algorithm, $algos, true ) ) {
52 self::$algo = $algorithm;
53 return $algorithm;
54 }
55 }
56
57 throw new DomainException( 'Could not find an acceptable hashing function.' );
58 }
59
68 public static function hashLength( $raw = true ) {
69 self::$hashLength ??= strlen( self::hash( '', true ) );
70 // Optimisation: Skip computing the length of non-raw hashes.
71 // The algos in hashAlgo() all produce a digest that is a multiple
72 // of 8 bits, where hex is always twice the length of binary byte length.
73 return $raw ? self::$hashLength : self::$hashLength * 2;
74 }
75
84 public static function hash( $data, $raw = true ) {
85 return hash( self::hashAlgo(), $data, $raw );
86 }
87
97 public static function hmac( $data, $key, $raw = true ) {
98 if ( !is_string( $key ) ) {
99 // hash_hmac tolerates non-string (would return null with warning)
100 throw new InvalidArgumentException( 'Invalid key type: ' . gettype( $key ) );
101 }
102 return hash_hmac( self::hashAlgo(), $data, $key, $raw );
103 }
104
105}
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...