|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Laravel Paystack package. |
| 5 | + * |
| 6 | + * (c) Prosper Otemuyiwa <[email protected]> |
| 7 | + * |
| 8 | + * Source http://stackoverflow.com/a/13733588/179104 |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Unicodeveloper\Paystack; |
| 15 | + |
| 16 | +class TransRef { |
| 17 | + |
| 18 | + public static function getPool( $type = 'alnum') |
| 19 | + { |
| 20 | + switch ( $type ) { |
| 21 | + case 'alnum': |
| 22 | + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 23 | + break; |
| 24 | + case 'alpha': |
| 25 | + $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 26 | + break; |
| 27 | + case 'hexdec': |
| 28 | + $pool = '0123456789abcdef'; |
| 29 | + break; |
| 30 | + case 'numeric': |
| 31 | + $pool = '0123456789'; |
| 32 | + break; |
| 33 | + case 'nozero': |
| 34 | + $pool = '123456789'; |
| 35 | + break; |
| 36 | + case 'distinct': |
| 37 | + $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; |
| 38 | + break; |
| 39 | + default: |
| 40 | + $pool = (string) $type; |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + return $pool; |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | + public static function secure_crypt($min, $max) { |
| 49 | + $range = $max - $min; |
| 50 | + |
| 51 | + if ($range < 0) { |
| 52 | + return $min; // not so random... |
| 53 | + } |
| 54 | + |
| 55 | + $log = log($range, 2); |
| 56 | + $bytes = (int) ($log / 8) + 1; // length in bytes |
| 57 | + $bits = (int) $log + 1; // length in bits |
| 58 | + $filter = (int) (1 << $bits) - 1; // set all lower bits to 1 |
| 59 | + do { |
| 60 | + $rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) ); |
| 61 | + $rnd = $rnd & $filter; // discard irrelevant bits |
| 62 | + } while ($rnd >= $range); |
| 63 | + |
| 64 | + return $min + $rnd; |
| 65 | + } |
| 66 | + |
| 67 | + public static function getHashedToken($length = 25) |
| 68 | + { |
| 69 | + $token = ""; |
| 70 | + $max = strlen(static::getPool()); |
| 71 | + for ($i = 0; $i < $length; $i++) { |
| 72 | + $token .= static::getPool()[static::secure_crypt(0, $max)]; |
| 73 | + } |
| 74 | + |
| 75 | + return $token; |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments