MediaWiki  master
MWCryptHash.php
Go to the documentation of this file.
1 <?php
26 class MWCryptHash {
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_algos();
50  $preference = [ 'whirlpool', 'sha256', 'sha1', 'md5' ];
51 
52  foreach ( $preference as $algorithm ) {
53  if ( in_array( $algorithm, $algos ) ) {
54  self::$algo = $algorithm;
55 
56  return self::$algo;
57  }
58  }
59 
60  // We only reach here if no acceptable hash is found in the list, this should
61  // be a technical impossibility since most of php's hash list is fixed and
62  // some of the ones we list are available as their own native functions
63  // But since we already require at least 5.2 and hash() was default in
64  // 5.1.2 we don't bother falling back to methods like sha1 and md5.
65  throw new DomainException( "Could not find an acceptable hashing function in hash_algos()" );
66  }
67 
76  public static function hashLength( $raw = true ) {
77  $key = $raw ? 'binary' : 'hex';
78  if ( self::$hashLength[$key] === null ) {
79  self::$hashLength[$key] = strlen( self::hash( '', $raw ) );
80  }
81 
82  // @phan-suppress-next-line PhanTypeMismatchReturnNullable False positive
83  return self::$hashLength[$key];
84  }
85 
94  public static function hash( $data, $raw = true ) {
95  return hash( self::hashAlgo(), $data, $raw );
96  }
97 
107  public static function hmac( $data, $key, $raw = true ) {
108  if ( !is_string( $key ) ) {
109  // hash_hmac tolerates non-string (would return null with warning)
110  throw new InvalidArgumentException( 'Invalid key type: ' . gettype( $key ) );
111  }
112  return hash_hmac( self::hashAlgo(), $data, $key, $raw );
113  }
114 
115 }
static $hashLength
The number of bytes outputted by the hash algorithm.
Definition: MWCryptHash.php:35
static hashAlgo()
Decide on the best acceptable hash algorithm we have available for hash()
Definition: MWCryptHash.php:44
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:76
static $algo
The hash algorithm being used.
Definition: MWCryptHash.php:30
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
static hash( $data, $raw=true)
Generate an acceptably unstable one-way-hash of some text making use of the best hash algorithm that ...
Definition: MWCryptHash.php:94