MediaWiki  1.34.0
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  true => null,
37  false => null,
38  ];
39 
44  public static function hashAlgo() {
45  if ( !is_null( self::$algo ) ) {
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  $raw = (bool)$raw;
78  if ( is_null( self::$hashLength[$raw] ) ) {
79  self::$hashLength[$raw] = strlen( self::hash( '', $raw ) );
80  }
81 
82  return self::$hashLength[$raw];
83  }
84 
93  public static function hash( $data, $raw = true ) {
94  return hash( self::hashAlgo(), $data, $raw );
95  }
96 
106  public static function hmac( $data, $key, $raw = true ) {
107  if ( !is_string( $key ) ) {
108  // a fatal error in HHVM; an exception will at least give us a stack trace
109  throw new InvalidArgumentException( 'Invalid key type: ' . gettype( $key ) );
110  }
111  return hash_hmac( self::hashAlgo(), $data, $key, $raw );
112  }
113 
114 }
MWCryptHash\hmac
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
Definition: MWCryptHash.php:106
MWCryptHash\hash
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:93
MWCryptHash\hashLength
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
MWCryptHash
Definition: MWCryptHash.php:26
MWCryptHash\$algo
static $algo
The hash algorithm being used.
Definition: MWCryptHash.php:30
MWCryptHash\hashAlgo
static hashAlgo()
Decide on the best acceptable hash algorithm we have available for hash()
Definition: MWCryptHash.php:44
MWCryptHash\$hashLength
static $hashLength
The number of bytes outputted by the hash algorithm.
Definition: MWCryptHash.php:35