MediaWiki REL1_39
MWCryptHash.php
Go to the documentation of this file.
1<?php
30 protected static $algo = null;
31
35 protected static $hashLength = [
36 'binary' => null,
37 'hex' => null,
38 ];
39
44 public static function hashAlgo() {
45 if ( self::$algo !== null ) {
46 return self::$algo;
47 }
48
49 $algos = hash_hmac_algos();
50 $preference = [ 'whirlpool', 'sha256' ];
51
52 foreach ( $preference as $algorithm ) {
53 if ( in_array( $algorithm, $algos, true ) ) {
54 self::$algo = $algorithm;
55 return self::$algo;
56 }
57 }
58
59 throw new DomainException( 'Could not find an acceptable hashing function.' );
60 }
61
70 public static function hashLength( $raw = true ) {
71 $key = $raw ? 'binary' : 'hex';
72 if ( self::$hashLength[$key] === null ) {
73 self::$hashLength[$key] = strlen( self::hash( '', $raw ) );
74 }
75
76 // @phan-suppress-next-line PhanTypeMismatchReturnNullable False positive
77 return self::$hashLength[$key];
78 }
79
88 public static function hash( $data, $raw = true ) {
89 return hash( self::hashAlgo(), $data, $raw );
90 }
91
101 public static function hmac( $data, $key, $raw = true ) {
102 if ( !is_string( $key ) ) {
103 // hash_hmac tolerates non-string (would return null with warning)
104 throw new InvalidArgumentException( 'Invalid key type: ' . gettype( $key ) );
105 }
106 return hash_hmac( self::hashAlgo(), $data, $key, $raw );
107 }
108
109}
static $hashLength
The number of bytes outputted by the hash algorithm.
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 $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...