예제 #1
0
 /**
  * Encrypt a string
  * 
  * @param string $plaintext
  * @return string
  */
 public function encrypt($plaintext)
 {
     $nonce = \Sodium::randombytes_buf(\Sodium::CRYPTO_SECRETBOX_NONCEBYTES);
     $encrypted = \base64_encode($nonce . \Sodium::crypto_secretbox(\json_encode($plaintext), $nonce, $this->key->getKey()));
     \Sodium::memzero($plaintext);
     return $encrypted;
 }
예제 #2
0
 /**
  * Get a new salt for use with 
  * 
  * @return string
  */
 public static function newPasswordSalt()
 {
     return \Sodium::randombytes_buf(\Sodium::CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES);
 }
/**
 * If the libsodium PHP extension is loaded, we'll use it above any other
 * solution.
 *
 * libsodium-php project:
 * @ref https://github.com/jedisct1/libsodium-php
 *
 * @param int $bytes
 *
 * @throws Exception
 *
 * @return string
 */
function random_bytes($bytes)
{
    try {
        $bytes = RandomCompat_intval($bytes);
    } catch (TypeError $ex) {
        throw new TypeError('random_bytes(): $bytes must be an integer');
    }
    if ($bytes < 1) {
        throw new Error('Length must be greater than 0');
    }
    /**
     * \Sodium\randombytes_buf() doesn't allow more than 2147483647 bytes to be
     * generated in one invocation.
     */
    if ($bytes > 2147483647) {
        $buf = '';
        for ($i = 0; $i < $bytes; $i += 1073741824) {
            $n = $bytes - $i > 1073741824 ? 1073741824 : $bytes - $i;
            $buf .= Sodium::randombytes_buf($n);
        }
    } else {
        $buf = Sodium::randombytes_buf($bytes);
    }
    if ($buf !== false) {
        if (RandomCompat_strlen($buf) === $bytes) {
            return $buf;
        }
    }
    /**
     * If we reach here, PHP has failed us.
     */
    throw new Exception('Could not gather sufficient random data');
}