3 * A cryptographic random generator class used for generating secret keys
5 * This is based in part on Drupal code as well as what we used in our own code
6 * prior to introduction of this class.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @author Daniel Friesen
27 use MediaWiki\MediaWikiServices
;
33 protected static function singleton() {
34 return MediaWikiServices
::getInstance()->getCryptRand();
38 * Return a boolean indicating whether or not the source used for cryptographic
39 * random bytes generation in the previously run generate* call
40 * was cryptographically strong.
42 * @return bool Returns true if the source was strong, false if not.
44 public static function wasStrong() {
45 return self
::singleton()->wasStrong();
49 * Generate a run of (ideally) cryptographically random data and return
50 * it in raw binary form.
51 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
52 * was cryptographically strong.
54 * @param int $bytes The number of bytes of random data to generate
55 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
56 * strong sources of entropy even if reading from them may steal
57 * more entropy from the system than optimal.
58 * @return string Raw binary random data
60 public static function generate( $bytes, $forceStrong = false ) {
61 return self
::singleton()->generate( $bytes, $forceStrong );
65 * Generate a run of (ideally) cryptographically random data and return
66 * it in hexadecimal string format.
67 * You can use MWCryptRand::wasStrong() if you wish to know if the source used
68 * was cryptographically strong.
70 * @param int $chars The number of hex chars of random data to generate
71 * @param bool $forceStrong Pass true if you want generate to prefer cryptographically
72 * strong sources of entropy even if reading from them may steal
73 * more entropy from the system than optimal.
74 * @return string Hexadecimal random data
76 public static function generateHex( $chars, $forceStrong = false ) {
77 return self
::singleton()->generateHex( $chars, $forceStrong );