本文整理汇总了PHP中mcrypt_create_iv函数的典型用法代码示例。如果您正苦于以下问题:PHP mcrypt_create_iv函数的具体用法?PHP mcrypt_create_iv怎么用?PHP mcrypt_create_iv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mcrypt_create_iv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: encrypt
/**
* Encrypt a string using Mcrypt.
*
* The string will be encrypted using the AES-256 scheme and will be base64 encoded.
*
* @param string $value
* @return string
*/
public static function encrypt($value)
{
$iv = mcrypt_create_iv(static::iv_size(), static::randomizer());
$value = static::pad($value);
$value = mcrypt_encrypt(static::$cipher, static::key(), $value, static::$mode, $iv);
return base64_encode($iv . $value);
}
示例2: confirmAction
public function confirmAction()
{
if (!$this->getRequest()->getParam('id')) {
return $this->_redirect('/registration');
}
// Check if the user exists and has not already been activated
$user_mapper = new Application_Model_UserMapper();
$user = $user_mapper->find($this->getRequest()->getParam('id'));
if ($user && !$user->getActive()) {
/**
* Generate a random activation key unique to the account. Insert
* it into a link, and email it to the user. If the user opens the
* link within 24 hours, the account will be activated
*/
$user_activation_mapper = new Application_Model_UserActivationMapper();
$user_activation = new Application_Model_UserActivation();
$activation_key = '';
$duplicate_activation_key = true;
while ($duplicate_activation_key) {
$random = mcrypt_create_iv(64);
$activation_key = hash('sha256', $random . $user->getPassword_salt() . $user->getUsername() . $user->getPassword_hash());
$duplicate_activation_key = $user_activation_mapper->findByActivation_key($activation_key);
}
$user_activation->setUser_id($user->getId())->setActivation_key($activation_key)->setCreated(date('Y-m-d H:i:s'));
$user_activation_mapper->save($user_activation, true);
$to = $user->getEmail();
$subject = 'User Activation';
$txt = "You have registered on zf1.\n <br/>\n <br/>\n To activate the account, follow this <a href='zf1.local/registration/activate/activation_key/{$activation_key}'>link</a>.\n <br/>\n <br/>\n This link will expire after 24 hours.\n <br/>\n If you follow the link after it expires and the account has not already been activated,\n <br/>\n another email will be sent with a fresh link.\n <br/>\n <br/>\n An email can also be sent by attempting to sign in with an account that has been registered but not yet activated.";
$headers = '';
// mail($to, $subject, $txt, $headers);
mail($to, $subject, $txt);
} else {
return $this->_redirect('/');
}
}
示例3: __construct
public function __construct($_key = '', $_bit = 128, $_type = 'ecb', $_use_base64 = true)
{
// 加密字节
if (192 === $_bit) {
$this->_bit = MCRYPT_RIJNDAEL_192;
} elseif (128 === $_bit) {
$this->_bit = MCRYPT_RIJNDAEL_128;
} else {
$this->_bit = MCRYPT_RIJNDAEL_256;
}
// 加密方法
if ('cfb' === $_type) {
$this->_type = MCRYPT_MODE_CFB;
} elseif ('cbc' === $_type) {
$this->_type = MCRYPT_MODE_CBC;
} elseif ('nofb' === $_type) {
$this->_type = MCRYPT_MODE_NOFB;
} elseif ('ofb' === $_type) {
$this->_type = MCRYPT_MODE_OFB;
} elseif ('stream' === $_type) {
$this->_type = MCRYPT_MODE_STREAM;
} else {
$this->_type = MCRYPT_MODE_ECB;
}
// 密钥
if (!empty($_key)) {
$this->_key = $_key;
}
// 是否使用base64
$this->_use_base64 = $_use_base64;
$this->_iv_size = mcrypt_get_iv_size($this->_bit, $this->_type);
$this->_iv = mcrypt_create_iv($this->_iv_size, MCRYPT_RAND);
}
示例4: decode
public static function decode($decrypt, $key)
{
$decoded = base64_decode($decrypt);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB), MCRYPT_RAND);
$decrypted = mcrypt_decrypt(MCRYPT_DES, $key, $decoded, MCRYPT_MODE_ECB, $iv);
return $decrypted;
}
示例5: _decrypt
private static function _decrypt($value, $key)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($value), MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
示例6: hash
/**
* Generate bcrypt hash of string
* @return string|FALSE
* @param $pw string
* @param $salt string
* @param $cost int
**/
function hash($pw, $salt = NULL, $cost = self::COST)
{
if ($cost < 4 || $cost > 31) {
user_error(self::E_CostArg, E_USER_ERROR);
}
$len = 22;
if ($salt) {
if (!preg_match('/^[[:alnum:]\\.\\/]{' . $len . ',}$/', $salt)) {
user_error(self::E_SaltArg, E_USER_ERROR);
}
} else {
$raw = 16;
$iv = '';
if (extension_loaded('mcrypt')) {
$iv = mcrypt_create_iv($raw, MCRYPT_DEV_URANDOM);
}
if (!$iv && extension_loaded('openssl')) {
$iv = openssl_random_pseudo_bytes($raw);
}
if (!$iv) {
for ($i = 0; $i < $raw; $i++) {
$iv .= chr(mt_rand(0, 255));
}
}
$salt = str_replace('+', '.', base64_encode($iv));
}
$salt = substr($salt, 0, $len);
$hash = crypt($pw, sprintf('$2y$%02d$', $cost) . $salt);
return strlen($hash) > 13 ? $hash : FALSE;
}
示例7: phpFreaksCrypto
function phpFreaksCrypto($key = 'a843l?nv89rjfd}O(jdnsleken0', $iv = false, $algorithm = 'tripledes', $mode = 'ecb')
{
if (extension_loaded('mcrypt') === FALSE) {
//$prefix = (PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : '';
//dl($prefix . 'mcrypt.' . PHP_SHLIB_SUFFIX) or die('The Mcrypt module could not be loaded.');
die('The Mcrypt module is not loaded and is required.');
}
if ($mode != 'ecb' && $iv === false) {
/*
the iv must remain the same from encryption to decryption and is usually
passed into the encrypted string in some form, but not always.
*/
die('In order to use encryption modes other then ecb, you must specify a unique and consistent initialization vector.');
}
// set mcrypt mode and cipher
$this->td = mcrypt_module_open($algorithm, '', $mode, '');
// Unix has better pseudo random number generator then mcrypt, so if it is available lets use it!
//$random_seed = strstr(PHP_OS, "WIN") ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
$random_seed = MCRYPT_RAND;
// if initialization vector set in constructor use it else, generate from random seed
$iv = $iv === false ? mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), $random_seed) : substr($iv, 0, mcrypt_enc_get_iv_size($this->td));
// get the expected key size based on mode and cipher
$expected_key_size = mcrypt_enc_get_key_size($this->td);
// we dont need to know the real key, we just need to be able to confirm a hashed version
$key = substr(md5($key), 0, $expected_key_size);
// initialize mcrypt library with mode/cipher, encryption key, and random initialization vector
mcrypt_generic_init($this->td, $key, $iv);
}
示例8: encryptString
/**
* Encrypts a string using AES
*
* @param string $stringToEncrypt The plaintext to encrypt
* @param bool $base64encoded Should I Base64-encode the result?
*
* @return string The cryptotext. Please note that the first 16 bytes of the raw string is the IV (initialisation vector) which is necessary for decoding the string.
*/
public function encryptString($stringToEncrypt, $base64encoded = true)
{
// Calculate the key to use for encryption
$keySize = mcrypt_get_key_size($this->_cipherType, $this->_cipherMode);
if (strlen($this->_keyString) != 32) {
$key = hash('sha256', $this->_keyString, true);
} else {
$key = $this->_keyString;
}
// Set up the IV (Initialization Vector)
$iv_size = mcrypt_get_iv_size($this->_cipherType, $this->_cipherMode);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
if (empty($iv)) {
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_RANDOM);
}
if (empty($iv)) {
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
// Encrypt the data
$cipherText = mcrypt_encrypt($this->_cipherType, $key, $stringToEncrypt, $this->_cipherMode, $iv);
// Prepend the IV to the ciphertext
$cipherText = $iv . $cipherText;
// Optionally pass the result through Base64 encoding
if ($base64encoded) {
$cipherText = base64_encode($cipherText);
}
// Return the result
return $cipherText;
}
示例9: gen_bytes
function gen_bytes($count)
{
if (function_exists('random_bytes')) {
return random_bytes($count);
} else {
if (function_exists('openssl_random_pseudo_bytes')) {
return openssl_random_pseudo_bytes($count);
} else {
if (function_exists('mcrypt_create_iv')) {
return mcrypt_create_iv($count);
} else {
if (is_readable('/dev/random')) {
$f = fopen("/dev/random", "rb");
$b = fread($f, $count);
fclose($f);
return $b;
} else {
if (is_readable('/dev/urandom')) {
$f = fopen("/dev/urandom", "rb");
$rand = fread($f, $count);
fclose($f);
return $rand;
} else {
$rand = "";
for ($a = 0; $a < $count; $a++) {
$rand .= chr(mt_rand(0, 255));
}
return $rand;
}
}
}
}
}
}
示例10: testHashVerify
public function testHashVerify()
{
$iv = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$this->assertEquals(true, $this->passwordEncoder->verify($this->passwordEncoder->hash('password'), 'password'));
$this->assertEquals(true, $this->passwordEncoder->verify($this->passwordEncoder->hash('password', $iv), 'password'));
$this->assertEquals(false, $this->passwordEncoder->verify($this->passwordEncoder->hash('password'), 'notThePassword'));
}
示例11: getToken
private function getToken($userID, $userName, $userRole)
{
$tokenId = base64_encode(mcrypt_create_iv(32));
$issuedAt = time();
$notBefore = $issuedAt + 10;
$expire = $notBefore + 90000;
$serverName = $_SERVER['SERVER_NAME'];
/*
* Create the token as an array
*/
$payload = ['userID' => $userID, 'userName' => $userName, 'userRole' => $userRole];
$data = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'user' => $payload];
// Store key in local file, not in php
$privateKey = $this->utils->readFile('private/apikey');
$secretKey = base64_decode($privateKey);
/*
* Encode the array to a JWT string.
* Second parameter is the key to encode the token.
*
* The output string can be validated at http://jwt.io/
*/
$jwt = JWT::encode($data, $secretKey, 'HS512');
$unencodedArray = ['data' => $payload, 'token' => $jwt];
echo json_encode($unencodedArray);
}
示例12: encrypt
/**
* Encrypt data for security
*
* @param mixed $data
* @return string
*/
public static function encrypt($data)
{
// Don't do anything with empty data
$data = trim($data);
if (empty($data)) {
return null;
}
// Check if encryption was turned off
if (MagebridgeModelConfig::load('encryption') == 0) {
return $data;
}
// Check if SSL is already in use, so encryption is not needed
if (MagebridgeModelConfig::load('protocol') == 'https') {
return $data;
}
// Check for mcrypt
if (!function_exists('mcrypt_get_iv_size') || !function_exists('mcrypt_cfb')) {
return $data;
}
// Generate a random key
$random = str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
$key = MageBridgeEncryptionHelper::getSaltedKey($random);
try {
$td = mcrypt_module_open(MCRYPT_CAST_256, '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$encrypted = mcrypt_generic($td, $data);
$encoded = MageBridgeEncryptionHelper::base64_encode($encrypted);
} catch (Exception $e) {
Mage::getSingleton('magebridge/debug')->error("Error while decrypting: " . $e->getMessage());
return null;
}
return $encoded . '|=|' . $random;
}
示例13: encrypt
/**
* Encrypt a string.
*
* @param string $str String to encrypt.
*
* @return string
*/
public function encrypt($str)
{
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
$str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->key, $str, MCRYPT_MODE_CBC, $iv);
$str = $iv . $str;
return base64_encode($str);
}
示例14: login
/**
* funkce obstaravajici prihlaseni uzivatele
*/
private function login()
{
$this->database = $this->context->getService("database.default.context");
$data = Nette\Utils\Json::decode($this->request->getParameters()["data"]);
$authenticator = new LoginAuthenticator($this->database);
$user = $this->getUser();
$user->setAuthenticator($authenticator);
try {
$user->login($data->username, $data->password);
} catch (Nette\Security\AuthenticationException $e) {
$error["err"] = true;
$error["message"] = $e->getMessage();
return $error;
}
$userIdent = (array) $user->getIdentity()->getData();
$tokenId = base64_encode(mcrypt_create_iv(32));
$issuedAt = time();
$notBefore = $issuedAt;
$expire = $notBefore + 60 * 60;
$serverName = "lolnotepad";
$token = ['iat' => $issuedAt, 'jti' => $tokenId, 'iss' => $serverName, 'nbf' => $notBefore, 'exp' => $expire, 'data' => $userIdent];
$key = base64_decode(KEY);
$jwt = JWT::encode($token, $key, 'HS256');
return $jwt;
}
示例15: computeSign
public function computeSign($sharedSecret)
{
if (!$this->isValid) {
throw new Exception(__METHOD__ . ": Message was not validated.");
}
try {
$bytesHash = sha1($this->GetSignatureBase(), true);
$sharedSecret = pack('H*', $sharedSecret);
// uprava pre PHP < 5.0
if (strlen($bytesHash) != 20) {
$bytes = "";
for ($i = 0; $i < strlen($bytesHash); $i += 2) {
$bytes .= chr(hexdec(substr($str, $i, 2)));
}
$bytesHash = $bytes;
}
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_ECB, "");
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_RAND);
mcrypt_generic_init($cipher, $sharedSecret, $iv);
$text = $this->pad(substr($bytesHash, 0, 16), mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
$bytesSign = mcrypt_generic($cipher, $text);
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);
$sign = substr(strtoupper(bin2hex($bytesSign)), 0, 32);
} catch (Exception $e) {
return false;
}
return $sign;
}