Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
MWCryptRand
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 generateHex
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @author Daniel Friesen
5 */
6
7namespace MediaWiki\Utils;
8
9/**
10 * A cryptographic random generator class used for generating secret keys
11 *
12 * This is based in part on Drupal code as well as what we used in our own code
13 * prior to introduction of this class.
14 */
15class MWCryptRand {
16
17    /**
18     * Generate a run of cryptographically random data and return
19     * it in hexadecimal string format.
20     *
21     * @param int $chars The number of hex chars of random data to generate
22     * @return string Hexadecimal random data
23     */
24    public static function generateHex( $chars ) {
25        // hex strings are 2x the length of raw binary so we divide the length in half
26        // odd numbers will result in a .5 that leads the generate() being 1 character
27        // short, so we use ceil() to ensure that we always have enough bytes
28        $bytes = ceil( $chars / 2 );
29        // Generate the data and then convert it to a hex string
30        $hex = bin2hex( random_bytes( $bytes ) );
31
32        // A bit of paranoia here, the caller asked for a specific length of string
33        // here, and it's possible (eg when given an odd number) that we may actually
34        // have at least 1 char more than they asked for. Just in case they made this
35        // call intending to insert it into a database that does truncation we don't
36        // want to give them too much and end up with their database and their live
37        // code having two different values because part of what we gave them is truncated
38        // hence, we strip out any run of characters longer than what we were asked for.
39        return substr( $hex, 0, $chars );
40    }
41}
42
43/** @deprecated class alias since 1.46 */
44class_alias( MWCryptRand::class, 'MWCryptRand' );