本文整理汇总了PHP中crypt_random_string函数的典型用法代码示例。如果您正苦于以下问题:PHP crypt_random_string函数的具体用法?PHP crypt_random_string怎么用?PHP crypt_random_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了crypt_random_string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: encrypt
/**
* Encrypt data.
*
* @param string $text Plaintext.
*
* @return array Array of MPI values (c1, c2).
*/
public function encrypt($text)
{
$p_len = strlen($this->_key->key['p']);
$length = $p_len - 11;
if ($length <= 0) {
return false;
}
$g = new Math_BigInteger($this->_key->key['g'], 256);
$p = new Math_BigInteger($this->_key->key['p'], 256);
$y = new Math_BigInteger($this->_key->key['y'], 256);
$out = array();
foreach (str_split($text, $length) as $m) {
// EME-PKCS1-v1_5 encoding
$psLen = $p_len - strlen($m) - 3;
$ps = '';
while (($psLen2 = strlen($ps)) != $psLen) {
$tmp = crypt_random_string($psLen - $psLen2);
$ps .= str_replace("", '', $tmp);
}
$em = new Math_BigInteger(chr(0) . chr(2) . $ps . chr(0) . $m, 256);
// End EME-PKCS1-v1_5 encoding
$k = Horde_Pgp_Crypt_DSA::randomNumber($p);
$c1 = $g->modPow($k, $p);
$c2_base = $y->modPow($k, $p)->multiply($em)->divide($p);
$c2 = $c2_base[1];
$out[] = str_pad($c1->toBytes(), $p_len, chr(0), STR_PAD_LEFT);
$out[] = str_pad($c2->toBytes(), $p_len, chr(0), STR_PAD_LEFT);
}
return $out;
}
示例2: encrypt_message
function encrypt_message($plaintext, $asym_key, $key_length = 150)
{
$rsa = new Crypt_RSA();
$rij = new Crypt_Rijndael();
// Generate Random Symmetric Key
$sym_key = crypt_random_string($key_length);
// Encrypt Message with new Symmetric Key
$rij->setKey($sym_key);
$ciphertext = $rij->encrypt($plaintext);
$ciphertext = base64_encode($ciphertext);
// Encrypted the Symmetric Key with the Asymmetric Key
$rsa->loadKey($asym_key);
$sym_key = $rsa->encrypt($sym_key);
// Base 64 encode the symmetric key for transport
$sym_key = base64_encode($sym_key);
$len = strlen($sym_key);
// Get the length
$len = dechex($len);
// The first 3 bytes of the message are the key length
$len = str_pad($len, 3, '0', STR_PAD_LEFT);
// Zero pad to be sure.
// Concatinate the length, the encrypted symmetric key, and the message
$message = $len . $sym_key . $ciphertext;
return $message;
}
示例3: testStringUniqueness
/**
* Takes a set of random values of length 128 bits and asserts all taken
* values are unique.
*/
public function testStringUniqueness()
{
$values = array();
for ($i = 0; $i < 10000; ++$i) {
$rand = crypt_random_string(16);
$this->assertSame(16, strlen($rand));
$this->assertArrayNotHasKey($rand, $values, 'Failed asserting that generated value does not exist in set.');
$values[$rand] = true;
}
}
示例4: randomNumber
/**
* Generate a number that lies between 0 and q-1.
*
* @param Math_BigInteger $q Max number.
*
* @return Math_BigInteger Generated number.
*/
public static function randomNumber($q)
{
$bytes = strlen($q->toBytes()) + 8;
$ints = $bytes + 1 >> 2;
$cstring = crypt_random_string($ints);
$random = '';
for ($i = 0; $i < $ints; ++$i) {
$random .= pack('N', $cstring[$i]);
}
$c = new Math_BigInteger(substr($random, 0, $bytes), 256);
$one = new Math_BigInteger(1);
$result_base = $c->divide($q->subtract($one));
return $result_base[1]->add($one);
}
示例5: encryptThenSign
/**
* Encrypt $plaintext with $secret, then date and sign the message.
*
* @param string $secret
* @param string $plaintext
* @return array
* Array(string $body, string $signature).
* Note that $body begins with an unencrypted envelope (ttl, iv).
* @throws InvalidMessageException
*/
public static function encryptThenSign($secret, $plaintext)
{
$iv = crypt_random_string(Constants::AES_BYTES);
$keys = AesHelper::deriveAesKeys($secret);
$cipher = new \Crypt_AES(CRYPT_AES_MODE_CBC);
$cipher->setKeyLength(Constants::AES_BYTES);
$cipher->setKey($keys['enc']);
$cipher->setIV($iv);
// JSON string; this will be signed but not encrypted
$jsonEnvelope = json_encode(array('ttl' => Time::getTime() + Constants::REQUEST_TTL, 'iv' => BinHex::bin2hex($iv)));
// JSON string; this will be signed and encrypted
$jsonEncrypted = $cipher->encrypt($plaintext);
$body = $jsonEnvelope . Constants::PROTOCOL_DELIM . $jsonEncrypted;
$signature = hash_hmac('sha256', $body, $keys['auth']);
return array($body, $signature);
}
示例6: encrypt
/**
* Encrypt the OAuth token
* @param \stdClass $token Serialized token object
* @return string
*/
public function encrypt($token)
{
// Encryption: we always use phpseclib for this
global $updraftplus;
$updraftplus->ensure_phpseclib('Crypt_AES', 'Crypt/AES');
$updraftplus->ensure_phpseclib('Crypt_Rijndael', 'Crypt/Rijndael');
if (!function_exists('crypt_random_string')) {
require_once UPDRAFTPLUS_DIR . '/includes/phpseclib/Crypt/Random.php';
}
$iv = crypt_random_string(self::IV_SIZE);
// Defaults to CBC mode
$rijndael = new Crypt_Rijndael();
$rijndael->setKey($this->key);
$rijndael->setIV($iv);
$cipherText = $rijndael->encrypt($token);
return base64_encode($iv . $cipherText);
}
示例7: genMasterKey
function genMasterKey($dirKey, $apacheGroup = "www-data")
{
if ($apacheGroup === "") {
$apacheGroup = "www-data";
}
$dirKey = rtrim($dirKey, "/");
$dirs = explode("/", $dirKey);
chdir("/");
foreach ($dirs as $dir) {
if ($dir === "") {
continue;
}
if (!file_exists($dir)) {
mkdir($dir, 0750);
chgrp($dir, $apacheGroup);
}
if (!is_readable($dir)) {
chmod($dir, 0750);
chgrp($dir, $apacheGroup);
}
chdir($dir);
}
$f = fopen($dirKey . "/.mediboard.key", "w");
if (!$f) {
echo "Failed to create key file!";
return 0;
}
fclose($f);
chmod(".mediboard.key", 0760);
chgrp(".mediboard.key", $apacheGroup);
$keyA = bin2hex(crypt_random_string(16));
$keyB = bin2hex(crypt_random_string(16));
$handle = fopen(".mediboard.key", "w");
if (!$handle) {
return 0;
}
fwrite($handle, $keyA . "\n" . $keyB);
fclose($handle);
chmod(".mediboard.key", 0750);
return 1;
}
示例8: encrypt
public static function encrypt($passphrases_and_keys, $message, $symmetric_algorithm = 9)
{
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($symmetric_algorithm);
if (!$cipher) {
throw new Exception("Unsupported cipher");
}
$prefix = crypt_random_string($key_block_bytes);
$prefix .= substr($prefix, -2);
$key = crypt_random_string($key_bytes);
$cipher->setKey($key);
$to_encrypt = $prefix . $message->to_bytes();
$mdc = new OpenPGP_ModificationDetectionCodePacket(hash('sha1', $to_encrypt . "Ó", true));
$to_encrypt .= $mdc->to_bytes();
$encrypted = array(new OpenPGP_IntegrityProtectedDataPacket($cipher->encrypt($to_encrypt)));
if (!is_array($passphrases_and_keys) && !$passphrases_and_keys instanceof IteratorAggregate) {
$passphrases_and_keys = (array) $passphrases_and_keys;
}
foreach ($passphrases_and_keys as $pass) {
if ($pass instanceof OpenPGP_PublicKeyPacket) {
if (!in_array($pass->algorithm, array(1, 2, 3))) {
throw new Exception("Only RSA keys are supported.");
}
$crypt_rsa = new OpenPGP_Crypt_RSA($pass);
$rsa = $crypt_rsa->public_key();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$esk = $rsa->encrypt(chr($symmetric_algorithm) . $key . pack('n', self::checksum($key)));
$esk = pack('n', OpenPGP::bitlength($esk)) . $esk;
array_unshift($encrypted, new OpenPGP_AsymmetricSessionKeyPacket($pass->algorithm, $pass->fingerprint(), $esk));
} else {
if (is_string($pass)) {
$s2k = new OpenPGP_S2K(crypt_random_string(10));
$cipher->setKey($s2k->make_key($pass, $key_bytes));
$esk = $cipher->encrypt(chr($symmetric_algorithm) . $key);
array_unshift($encrypted, new OpenPGP_SymmetricSessionKeyPacket($s2k, $esk, $symmetric_algorithm));
}
}
}
return new OpenPGP_Message($encrypted);
}
示例9: sign
/**
* Sign an X.509 certificate
*
* $issuer's private key needs to be loaded.
* $subject can be either an existing X.509 cert (if you want to resign it),
* a CSR or something with the DN and public key explicitly set.
*
* @param File_X509 $issuer
* @param File_X509 $subject
* @param string $signatureAlgorithm optional
* @access public
* @return mixed
*/
function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption')
{
if (!is_object($issuer->privateKey) || empty($issuer->dn)) {
return false;
}
if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) {
return false;
}
$currentCert = isset($this->currentCert) ? $this->currentCert : null;
$signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null;
if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) {
$this->currentCert = $subject->currentCert;
$this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm;
$this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm;
if (!empty($this->startDate)) {
$this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate);
}
if (!empty($this->endDate)) {
$this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate);
}
if (!empty($this->serialNumber)) {
$this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber;
}
if (!empty($subject->dn)) {
$this->currentCert['tbsCertificate']['subject'] = $subject->dn;
}
if (!empty($subject->publicKey)) {
$this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey;
}
$this->removeExtension('id-ce-authorityKeyIdentifier');
if (isset($subject->domains)) {
$this->removeExtension('id-ce-subjectAltName');
}
} elseif (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) {
return false;
} else {
if (!isset($subject->publicKey)) {
return false;
}
$startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O');
$endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year'));
if (!empty($this->serialNumber)) {
$serialNumber = $this->serialNumber;
} else {
if (!function_exists('crypt_random_string')) {
include_once 'Crypt/Random.php';
}
/* "The serial number MUST be a positive integer"
"Conforming CAs MUST NOT use serialNumber values longer than 20 octets."
-- https://tools.ietf.org/html/rfc5280#section-4.1.2.2
for the integer to be positive the leading bit needs to be 0 hence the
application of a bitmap
*/
$serialNumber = new Math_BigInteger(crypt_random_string(20) & "" . str_repeat("ÿ", 19), 256);
}
$this->currentCert = array('tbsCertificate' => array('version' => 'v3', 'serialNumber' => $serialNumber, 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, 'validity' => array('notBefore' => $this->_timeField($startDate), 'notAfter' => $this->_timeField($endDate)), 'subject' => $subject->dn, 'subjectPublicKeyInfo' => $subjectPublicKey), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false);
// Copy extensions from CSR.
$csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0);
if (!empty($csrexts)) {
$this->currentCert['tbsCertificate']['extensions'] = $csrexts;
}
}
$this->currentCert['tbsCertificate']['issuer'] = $issuer->dn;
if (isset($issuer->currentKeyIdentifier)) {
$this->setExtension('id-ce-authorityKeyIdentifier', array('keyIdentifier' => $issuer->currentKeyIdentifier));
//$extensions = &$this->currentCert['tbsCertificate']['extensions'];
//if (isset($issuer->serialNumber)) {
// $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber;
//}
//unset($extensions);
}
if (isset($subject->currentKeyIdentifier)) {
$this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier);
}
$altName = array();
if (isset($subject->domains) && count($subject->domains) > 1) {
$altName = array_map(array('File_X509', '_dnsName'), $subject->domains);
}
if (isset($subject->ipAddresses) && count($subject->ipAddresses)) {
// should an IP address appear as the CN if no domain name is specified? idk
//$ips = count($subject->domains) ? $subject->ipAddresses : array_slice($subject->ipAddresses, 1);
$ipAddresses = array();
foreach ($subject->ipAddresses as $ipAddress) {
$encoded = $subject->_ipAddress($ipAddress);
if ($encoded !== false) {
$ipAddresses[] = $encoded;
//.........这里部分代码省略.........
示例10: crypt_random_string
/**
* Generate a random string.
*
* Although microoptimizations are generally discouraged as they impair readability this function is ripe with
* microoptimizations because this function has the potential of being called a huge number of times.
* eg. for RSA key generation.
*
* @param Integer $length
* @return String
* @access public
*/
function crypt_random_string($length)
{
if (CRYPT_RANDOM_IS_WINDOWS) {
// method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
// ie. class_alias is a function that was introduced in PHP 5.3
if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) {
return mcrypt_create_iv($length);
}
// method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
// to quote <http://php.net/ChangeLog-5.php#5.3.4>, "possible blocking behavior". as of 5.3.4
// openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both
// call php_win32_get_random_bytes():
//
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392
//
// php_win32_get_random_bytes() is defined thusly:
//
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
//
// we're calling it, all the same, in the off chance that the mcrypt extension is not available
if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
return openssl_random_pseudo_bytes($length);
}
} else {
// method 1. the fastest
if (function_exists('openssl_random_pseudo_bytes')) {
return openssl_random_pseudo_bytes($length);
}
// method 2
static $fp = true;
if ($fp === true) {
// warning's will be output unles the error suppression operator is used. errors such as
// "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc.
$fp = @fopen('/dev/urandom', 'rb');
}
if ($fp !== true && $fp !== false) {
// surprisingly faster than !is_bool() or is_resource()
return fread($fp, $length);
}
// method 3. pretty much does the same thing as method 2 per the following url:
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391
// surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
// not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
// restrictions or some such
if (function_exists('mcrypt_create_iv')) {
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
}
}
// at this point we have no choice but to use a pure-PHP CSPRNG
// cascade entropy across multiple PHP instances by fixing the session and collecting all
// environmental variables, including the previous session data and the current session
// data.
//
// mt_rand seeds itself by looking at the PID and the time, both of which are (relatively)
// easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but
// PHP isn't low level to be able to use those as sources and on a web server there's not likely
// going to be a ton of keyboard or mouse action. web servers do have one thing that we can use
// however. a ton of people visiting the website. obviously you don't want to base your seeding
// soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled
// by the user and (2) this isn't just looking at the data sent by the current user - it's based
// on the data sent by all users. one user requests the page and a hash of their info is saved.
// another user visits the page and the serialization of their data is utilized along with the
// server envirnment stuff and a hash of the previous http request data (which itself utilizes
// a hash of the session data before that). certainly an attacker should be assumed to have
// full control over his own http requests. he, however, is not going to have control over
// everyone's http requests.
static $crypto = false, $v;
if ($crypto === false) {
// save old session data
$old_session_id = session_id();
$old_use_cookies = ini_get('session.use_cookies');
$old_session_cache_limiter = session_cache_limiter();
if (isset($_SESSION)) {
$_OLD_SESSION = $_SESSION;
}
if ($old_session_id != '') {
session_write_close();
}
session_id(1);
ini_set('session.use_cookies', 0);
session_cache_limiter('');
session_start();
$v = $seed = $_SESSION['seed'] = pack('H*', sha1(serialize($_SERVER) . serialize($_POST) . serialize($_GET) . serialize($_COOKIE) . serialize($GLOBALS) . serialize($_SESSION) . serialize($_OLD_SESSION)));
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
}
$_SESSION['count']++;
session_write_close();
//.........这里部分代码省略.........
示例11: generateRandomBytes
private function generateRandomBytes($length)
{
return crypt_random_string($length);
}
示例12: _rsa_crypt
/**
* RSA Encrypt
*
* Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e
* should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that
* calls this call modexp, instead, but I think this makes things clearer, maybe...
*
* @see Net_SSH1::Net_SSH1()
* @param Math_BigInteger $m
* @param Array $key
* @return Math_BigInteger
* @access private
*/
function _rsa_crypt($m, $key)
{
/*
if (!class_exists('Crypt_RSA')) {
include_once 'Crypt/RSA.php';
}
$rsa = new Crypt_RSA();
$rsa->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
return $rsa->encrypt($m);
*/
// To quote from protocol-1.5.txt:
// The most significant byte (which is only partial as the value must be
// less than the public modulus, which is never a power of two) is zero.
//
// The next byte contains the value 2 (which stands for public-key
// encrypted data in the PKCS standard [PKCS#1]). Then, there are non-
// zero random bytes to fill any unused space, a zero byte, and the data
// to be encrypted in the least significant bytes, the last byte of the
// data in the least significant byte.
// Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation",
// under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL:
// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
$modulus = $key[1]->toBytes();
$length = strlen($modulus) - strlen($m) - 3;
$random = '';
while (strlen($random) != $length) {
$block = crypt_random_string($length - strlen($random));
$block = str_replace("", '', $block);
$random .= $block;
}
$temp = chr(0) . chr(2) . $random . chr(0) . $m;
$m = new Math_BigInteger($temp, 256);
$m = $m->modPow($key[0], $key[1]);
return $m->toBytes();
}
示例13: getRandomBinaryString
/**
* Generate a pseudo random binary string
*
* @param int $length Binary string length
*
* @return string
*/
static function getRandomBinaryString($length)
{
return crypt_random_string($length);
}
示例14: encryptString
function encryptString($pwd = null, $iv_field = "iv")
{
if (is_null($pwd)) {
$pwd = $this->password;
}
try {
$master_key_filepath = CAppUI::conf("master_key_filepath");
$master_key_filepath = rtrim($master_key_filepath, "/");
if (CExchangeSource::checkMasterKeyFile($master_key_filepath)) {
CAppUI::requireLibraryFile("phpseclib/phpseclib/Crypt/AES");
CAppUI::requireLibraryFile("phpseclib/phpseclib/Crypt/Random");
$cipher = new Crypt_AES(CRYPT_AES_MODE_CTR);
// keys are null-padded to the closest valid size
// longer than the longest key and it's truncated
$cipher->setKeyLength(256);
$keyAB = file($master_key_filepath . "/.mediboard.key");
if (count($keyAB) == 2) {
$cipher->setKey($keyAB[0] . $keyAB[1]);
$iv = bin2hex(crypt_random_string(16));
$this->{$iv_field} = $iv;
$cipher->setIV($iv);
$encrypted = rtrim(base64_encode($cipher->encrypt($pwd)), "");
if ($encrypted) {
return $encrypted;
}
}
} else {
// Key is not available
$this->{$iv_field} = "";
}
} catch (Exception $e) {
return $pwd;
}
return $pwd;
}
示例15: create_RandomString
function create_RandomString($length = 32)
{
return bin2hex(crypt_random_string($length));
}