<?php
 class vB_Utility_Random { use vB_Utility_Trait_NoSerialize; private static $alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . 'abcdefghijklmnopqrstuvwxyz' . '0123456789'; public function alphanumeric($length) { return $this->string(self::$alphanum, $length); } public function string($characters, $length) { if ($length <= 0 OR !is_int($length)) { throw new Exception("Length must be a positive integer."); } if (!is_string($characters) OR !$characters) { throw new Exception("Charaacters must be a non empty string."); } $min = 0; $max = strlen($characters) - 1; $output = ''; for ($i = 0; $i < $length; $i++) { $output .= $characters[random_int($min, $max)]; } return $output; } public function hex($length = 32) { if ($length <= 0 OR !is_int($length)) { throw new Exception('Length must be a positive integer.'); } $bytes = ceil($length / 2); $printable_hex = bin2hex(random_bytes($bytes)); $digits = strlen($printable_hex); if ($digits < $length) { throw new Exception('Unexpected error: Generated hex was shorter than expected'); } else if ($digits > $length) { $printable_hex = substr($printable_hex, 0, $length); } return $printable_hex; } public function uuid_v4() : string { $uuid = bin2hex(random_bytes(16)); $printable_hex = sprintf('%08s-%04s-4%03s-%04x-%012s', substr($uuid, 0, 8), substr($uuid, 8, 4), substr($uuid, 13, 3), hexdec(substr($uuid, 16, 4)) & 0x3FFF | 0x8000, substr($uuid, 20, 12) ); return $printable_hex; } public function vbhash($length = 32) { return $this->hex($length); } public function nonsecureAlphanumeric($length) { return $this->nonsecureString(self::$alphanum, $length); } public function nonsecureString($characters, $length) { if ($length <= 0 OR !is_int($length)) { throw new Exception("Length must be a positive integer."); } if (!is_string($characters) OR !$characters) { throw new Exception("Characters must be a non empty string."); } $min = 0; $max = strlen($characters) - 1; $output = ''; for ($i = 0; $i < $length; $i++) { $output .= $characters[mt_rand($min, $max)]; } return $output; } } ?>
