| 1: | <?php
|
| 2: | |
| 3: | |
| 4: | |
| 5: | |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: |
|
| 11: |
|
| 12: | namespace Xmf;
|
| 13: |
|
| 14: | |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: |
|
| 24: | class Random
|
| 25: | {
|
| 26: | |
| 27: | |
| 28: | |
| 29: | |
| 30: | |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | |
| 37: |
|
| 38: | public static function generateOneTimeToken($hash = 'sha512', $bytes = 64)
|
| 39: | {
|
| 40: | if (function_exists('random_bytes')) {
|
| 41: | $randomData = random_bytes($bytes);
|
| 42: | } elseif (function_exists('openssl_random_pseudo_bytes')) {
|
| 43: | $crypto_strong = false;
|
| 44: | $randomData = openssl_random_pseudo_bytes($bytes, $crypto_strong);
|
| 45: |
|
| 46: | if ($randomData === false) {
|
| 47: | throw new Exception("Could not generate secure random bytes.");
|
| 48: | }
|
| 49: |
|
| 50: | if (!$crypto_strong) {
|
| 51: | throw new Exception("Non-cryptographically strong algorithm used for random bytes.");
|
| 52: | }
|
| 53: | } else {
|
| 54: | $randomData = md5(uniqid(mt_rand(), true));
|
| 55: | }
|
| 56: |
|
| 57: | if ($randomData === null) {
|
| 58: | throw new Exception("Failed to generate random data.");
|
| 59: | }
|
| 60: |
|
| 61: | $token = hash($hash, $randomData);
|
| 62: |
|
| 63: | return $token;
|
| 64: | }
|
| 65: |
|
| 66: | |
| 67: | |
| 68: | |
| 69: | |
| 70: | |
| 71: | |
| 72: | |
| 73: | |
| 74: | |
| 75: | |
| 76: | |
| 77: |
|
| 78: | public static function generateKey($hash = 'sha512', $bytes = 128)
|
| 79: | {
|
| 80: | if (function_exists('random_bytes')) {
|
| 81: | $randomData = random_bytes($bytes);
|
| 82: | } elseif (function_exists('openssl_random_pseudo_bytes')) {
|
| 83: | $crypto_strong = false;
|
| 84: | $randomData = openssl_random_pseudo_bytes($bytes, $crypto_strong);
|
| 85: |
|
| 86: | if ($randomData === false) {
|
| 87: | throw new Exception("Could not generate secure random bytes.");
|
| 88: | }
|
| 89: |
|
| 90: | if (!$crypto_strong) {
|
| 91: | throw new Exception("Non-cryptographically strong algorithm used for random bytes.");
|
| 92: | }
|
| 93: | } else {
|
| 94: | $randomData = md5(uniqid(mt_rand(), true));
|
| 95: | }
|
| 96: |
|
| 97: | if ($randomData === null) {
|
| 98: | throw new Exception("Failed to generate random data.");
|
| 99: | }
|
| 100: |
|
| 101: | $token = hash($hash, $randomData);
|
| 102: | return $token;
|
| 103: | }
|
| 104: | }
|
| 105: | |