function testRandom() { for ($i = 1; $i < 128; $i += 4) { $data = Crypto::random($i); $this->assertNotEqual($data, '', 'Empty random data generated'); $this->assert(strlen($data) == $i, 'Random data received was not the length requested'); } }
function getToken() { if (!$this->csrf['token'] || $this->isExpired()) { $this->csrf['token'] = sha1(session_id() . Crypto::random(16) . SECRET_SALT); $this->csrf['time'] = time(); } else { //Reset the timer $this->csrf['time'] = time(); } return $this->csrf['token']; }
function randCode($len = 8, $chars = false) { $chars = $chars ?: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_='; // Determine the number of bits we need $char_count = strlen($chars); $bits_per_char = ceil(log($char_count, 2)); $bytes = ceil(4 * $len / floor(32 / $bits_per_char)); // Pad to 4 byte boundary $bytes += (4 - $bytes % 4) % 4; // Fetch some random data blocks $data = Crypto::random($bytes); $mask = (1 << $bits_per_char) - 1; $loops = (int) (32 / $bits_per_char); $output = ''; $ints = unpack('V*', $data); foreach ($ints as $int) { for ($i = $loops; $i > 0; $i--) { $output .= $chars[($int & $mask) % $char_count]; $int >>= $bits_per_char; } } return substr($output, 0, $len); }
function rotate() { $this->csrf['token'] = sha1(session_id() . Crypto::random(16) . SECRET_SALT); $this->csrf['time'] = time(); }
function encrypt($text, $cid = 0) { if (!$this->exists() || !$text || !($cipher = $this->getCipher($cid)) || !($crypto = $this->getCrypto($cipher['cid']))) { return false; } $ivlen = $cipher['ivlen']; $iv = Crypto::random($ivlen); $crypto->setKey($this->getKeyHash($iv, $ivlen)); $crypto->setIV($iv); return sprintf('$%s$%s%s', $cipher['cid'], $iv, $crypto->encrypt($text)); }