本文整理汇总了PHP中phpseclib\Crypt\Random类的典型用法代码示例。如果您正苦于以下问题:PHP Random类的具体用法?PHP Random怎么用?PHP Random使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Random类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: encrypt
public static function encrypt($encryptionKey, $textInput, $blockType = 'CBC', $urlSafe = false)
{
switch ($blockType) {
case 'CBC':
$cipher = new Rijndael(Rijndael::MODE_CBC);
$cipher->setKey($encryptionKey);
$iv = Random::string($cipher->getBlockLength() >> 3);
$cipher->setIV($iv);
break;
case 'ECB':
$cipher = new Rijndael(Rijndael::MODE_ECB);
$cipher->setKey($encryptionKey);
$iv = '';
break;
default:
throw new \Exception('Unknown encryption blocktype: ' . $blockType, 500);
break;
}
$encryptedResult = $iv . $cipher->encrypt($textInput);
if ($urlSafe) {
return Base64URLSafe::urlsafe_b64encode($encryptedResult);
} else {
return base64_encode($encryptedResult);
}
}
示例2: addAuthHeaders
public function addAuthHeaders(BeforeEvent $event)
{
/*
* Get Consumer ID and Private Key from auth and then unset it
*/
$auth = $event->getClient()->getDefaultOption('auth');
if ($auth === null) {
throw new \Exception('Http client is missing \'auth\' parameters', 1466965269);
}
$consumerId = $auth[0];
$privateKey = $auth[1];
$event->getClient()->setDefaultOption('auth', null);
/*
* Get Request URL, method, and timestamp to calculate signature
*/
$requestUrl = $event->getRequest()->getUrl();
//decode url back to normal to nextCursor issue. automatic url encoding
$requestUrl = rawurldecode($requestUrl);
$event->getRequest()->setUrl($requestUrl);
$requestMethod = $event->getRequest()->getMethod();
$timestamp = Utils::getMilliseconds();
$signature = Signature::calculateSignature($consumerId, $privateKey, $requestUrl, $requestMethod, $timestamp);
/*
* Add required headers to request
*/
$headers = ['WM_SVC.NAME' => 'Walmart Marketplace', 'WM_QOS.CORRELATION_ID' => base64_encode(Random::string(16)), 'WM_SEC.TIMESTAMP' => $timestamp, 'WM_SEC.AUTH_SIGNATURE' => $signature, 'WM_CONSUMER.ID' => $consumerId];
$currentHeaders = $event->getRequest()->getHeaders();
unset($currentHeaders['Authorization']);
$updatedHeaders = array_merge($currentHeaders, $headers);
$event->getRequest()->setHeaders($updatedHeaders);
}
示例3: 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 BigInteger($this->_key->key['g'], 256);
$p = new BigInteger($this->_key->key['p'], 256);
$y = new 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 = Random::String($psLen - $psLen2);
$ps .= str_replace("", '', $tmp);
}
$em = new 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;
}
示例4:
function testEncryptDir_A128CBCHS256()
{
$secret = Random::string(256 / 8);
$jwe = new JOSE_JWE($this->plain_text);
$jwe = $jwe->encrypt($secret, 'dir');
$jwe_decoded = JOSE_JWT::decode($jwe->toString());
$this->assertEquals($this->plain_text, $jwe_decoded->decrypt($secret)->plain_text);
}
示例5: 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 = 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;
}
}
示例6: randomNumber
/**
* Generate a number that lies between 0 and q-1.
*
* @param \phpseclib\Math\BigInteger $q Max number.
*
* @return \phpseclib\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 BigInteger(substr($random, 0, $bytes), 256);
$one = new BigInteger(1);
$result_base = $c->divide($q->subtract($one));
return $result_base[1]->add($one);
}
示例7: handle
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$maxInt = 2147483647;
$min = new BigInteger(10000000.0);
$max = new BigInteger($maxInt);
$prime = $max->randomPrime($min, $max);
$a = new BigInteger($prime);
$b = new BigInteger($maxInt + 1);
if (!($inverse = $a->modInverse($b))) {
$this->error("An error accured during calculation. Please re-run 'php artisan rocid:generate'.");
return;
}
$random = hexdec(bin2hex(Random::string(4))) & $maxInt;
$this->info("Generated numbers (Paste these in config/rockid.php) :\nprime: {$prime}\ninverse: {$inverse}\nrandom: {$random}");
}
示例8: savePrivateKey
/**
* Convert a private key to the appropriate format.
*
* @access public
* @param \phpseclib\Math\BigInteger $n
* @param \phpseclib\Math\BigInteger $e
* @param \phpseclib\Math\BigInteger $d
* @param array $primes
* @param array $exponents
* @param array $coefficients
* @param string $password optional
* @return string
*/
static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, $primes, $exponents, $coefficients, $password = '')
{
$num_primes = count($primes);
$raw = array('version' => $num_primes == 2 ? chr(0) : chr(1), 'modulus' => $n->toBytes(true), 'publicExponent' => $e->toBytes(true), 'privateExponent' => $d->toBytes(true), 'prime1' => $primes[1]->toBytes(true), 'prime2' => $primes[2]->toBytes(true), 'exponent1' => $exponents[1]->toBytes(true), 'exponent2' => $exponents[2]->toBytes(true), 'coefficient' => $coefficients[2]->toBytes(true));
$components = array();
foreach ($raw as $name => $value) {
$components[$name] = pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($value)), $value);
}
$RSAPrivateKey = implode('', $components);
if ($num_primes > 2) {
$OtherPrimeInfos = '';
for ($i = 3; $i <= $num_primes; $i++) {
// OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
//
// OtherPrimeInfo ::= SEQUENCE {
// prime INTEGER, -- ri
// exponent INTEGER, -- di
// coefficient INTEGER -- ti
// }
$OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
$OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
$OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
$OtherPrimeInfos .= pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
}
$RSAPrivateKey .= pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
}
$RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
$rsaOID = Hex::decode('300d06092a864886f70d0101010500');
// hex version of MA0GCSqGSIb3DQEBAQUA
$RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_INTEGER, "", $rsaOID, 4, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
$RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
if (!empty($password) || is_string($password)) {
$salt = Random::string(8);
$iterationCount = 2048;
$crypto = new DES(DES::MODE_CBC);
$crypto->setPassword($password, 'pbkdf1', 'md5', $salt, $iterationCount);
$RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
$parameters = pack('Ca*a*Ca*N', self::ASN1_OCTETSTRING, self::_encodeLength(strlen($salt)), $salt, self::ASN1_INTEGER, self::_encodeLength(4), $iterationCount);
$pbeWithMD5AndDES_CBC = "*†H†÷\r";
$encryptionAlgorithm = pack('Ca*a*Ca*a*', self::ASN1_OBJECT, self::_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, self::ASN1_SEQUENCE, self::_encodeLength(strlen($parameters)), $parameters);
$RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, self::ASN1_OCTETSTRING, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
$RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
$RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(Base64::encode($RSAPrivateKey), 64) . '-----END ENCRYPTED PRIVATE KEY-----';
} else {
$RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(Base64::encode($RSAPrivateKey), 64) . '-----END PRIVATE KEY-----';
}
return $RSAPrivateKey;
}
示例9: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$prime = $input->getArgument('prime');
// Calculate the inverse.
$a = new BigInteger($prime);
$b = new BigInteger(Optimus::MAX_INT + 1);
if (!($inverse = $a->modInverse($b))) {
$output->writeln('<error>Invalid prime number</>');
return;
}
$rand = hexdec(bin2hex(Random::string(4))) & Optimus::MAX_INT;
$output->writeln('Prime: ' . $prime);
$output->writeln('Inverse: ' . $inverse);
$output->writeln('Random: ' . $rand);
$output->writeln('');
$output->writeln(' new Optimus(' . $prime . ', ' . $inverse . ', ' . $rand . ');');
}
示例10: 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 = Random::string($key_block_bytes);
$prefix .= substr($prefix, -2);
$key = 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(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);
}
示例11: wrapPrivateKey
/**
* Wrap a private key appropriately
*
* @access public
* @param string $algorithm
* @param string $key
* @param string $attr
* @param string $password
* @return string
*/
static function wrapPrivateKey($key, $algorithm, $attr, $password)
{
$asn1 = new ASN1();
$asn1->loadOIDs(oids);
$key = ['version' => 'v1', 'privateKeyAlgorithm' => ['algorithm' => $algorithm], 'privateKey' => Base64::encode($key)];
if (!empty($attr)) {
$key['attributes'] = $attr;
}
$key = $asn1->encodeDER($key, PrivateKeyInfo);
if (!empty($password) && is_string($password)) {
$salt = Random::string(8);
$iterationCount = self::$defaultIterationCount;
if (self::$defaultEncryptionAlgorithm == 'id-PBES2') {
$crypto = self::getPBES2EncryptionObject(self::$defaultEncryptionScheme);
$hash = str_replace('-', '/', substr(self::$defaultPRF, 11));
$kdf = 'pbkdf2';
$iv = Random::string($crypto->getBlockLength() >> 3);
$PBKDF2params = ['salt' => Base64::encode($salt), 'iterationCount' => $iterationCount, 'prf' => ['algorithm' => self::$defaultPRF, 'parameters' => null]];
$PBKDF2params = $asn1->encodeDER($PBKDF2params, PBKDF2params);
if (!$crypto instanceof RC2) {
$params = ['octetString' => Base64::encode($iv)];
} else {
$params = ['rc2ParametersVersion' => 58, 'iv' => Base64::encode($iv)];
$params = $asn1->encodeDER($params, RC2CBCParameter);
$params = new ASN1\Element($params);
}
$params = ['keyDerivationFunc' => ['algorithm' => 'id-PBKDF2', 'parameters' => new ASN1\Element($PBKDF2params)], 'encryptionScheme' => ['algorithm' => self::$defaultEncryptionScheme, 'parameters' => $params]];
$params = $asn1->encodeDER($params, PBES2params);
$crypto->setIV($iv);
} else {
$crypto = self::getPBES1EncryptionObject(self::$defaultEncryptionAlgorithm);
$hash = self::getPBES1Hash(self::$defaultEncryptionAlgorithm);
$kdf = self::getPBES1KDF(self::$defaultEncryptionAlgorithm);
$params = ['salt' => Base64::encode($salt), 'iterationCount' => $iterationCount];
$params = $asn1->encodeDER($params, PBEParameter);
}
$crypto->setPassword($password, $kdf, $hash, $salt, $iterationCount);
$key = $crypto->encrypt($key);
$key = ['encryptionAlgorithm' => ['algorithm' => self::$defaultEncryptionAlgorithm, 'parameters' => new ASN1\Element($params)], 'encryptedData' => Base64::encode($key)];
$key = $asn1->encodeDER($key, EncryptedPrivateKeyInfo);
return "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(Base64::encode($key), 64) . "-----END ENCRYPTED PRIVATE KEY-----";
}
return "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(Base64::encode($key), 64) . "-----END PRIVATE KEY-----";
}
示例12: 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 \phpseclib\File\X509 $issuer
* @param \phpseclib\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'));
/* "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 = !empty($this->serialNumber) ?
$this->serialNumber :
new BigInteger(Random::string(20) & ("\x7F" . str_repeat("\xFF", 19)), 256);
$this->currentCert = array(
'tbsCertificate' =>
array(
'version' => 'v3',
'serialNumber' => $serialNumber, // $this->setserialNumber()
'signature' => array('algorithm' => $signatureAlgorithm),
'issuer' => false, // this is going to be overwritten later
'validity' => array(
'notBefore' => $this->_timeField($startDate), // $this->setStartDate()
'notAfter' => $this->_timeField($endDate) // $this->setEndDate()
),
'subject' => $subject->dn,
'subjectPublicKeyInfo' => $subjectPublicKey
),
'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
'signature' => false // this is going to be overwritten later
);
// 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(
//.........这里部分代码省略.........
示例13: strlen
/**
* Sends Binary Packets
*
* Returns true on success, false on failure.
*
* @see \phpseclib\Net\SSH1::_get_binary_packet()
*
* @param String $data
*
* @return Boolean
* @access private
*/
function _send_binary_packet($data)
{
if (feof($this->fsock)) {
//user_error('connection closed prematurely');
return false;
}
$length = strlen($data) + 4;
$padding = Random::string(8 - ($length & 7));
$orig = $data;
$data = $padding . $data;
$data .= pack('N', $this->_crc($data));
if ($this->crypto !== false) {
$data = $this->crypto->encrypt($data);
}
$packet = pack('Na*', $length, $data);
$start = strtok(microtime(), ' ') + strtok('');
// http://php.net/microtime#61838
$result = strlen($packet) == fputs($this->fsock, $packet);
$stop = strtok(microtime(), ' ') + strtok('');
if (defined('NET_SSH1_LOGGING')) {
$temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN';
$temp = '-> ' . $temp . ' (' . round($stop - $start, 4) . 's)';
$this->_append_log($temp, $orig);
}
return $result;
}
示例14: savePrivateKey
/**
* Convert a private key to the appropriate format.
*
* @access public
* @param \phpseclib\Math\BigInteger $n
* @param \phpseclib\Math\BigInteger $e
* @param \phpseclib\Math\BigInteger $d
* @param array $primes
* @param array $exponents
* @param array $coefficients
* @param string $password optional
* @return string
*/
static function savePrivateKey(BigInteger $n, BigInteger $e, BigInteger $d, $primes, $exponents, $coefficients, $password = '')
{
$num_primes = count($primes);
$raw = array('version' => $num_primes == 2 ? chr(0) : chr(1), 'modulus' => $n->toBytes(true), 'publicExponent' => $e->toBytes(true), 'privateExponent' => $d->toBytes(true), 'prime1' => $primes[1]->toBytes(true), 'prime2' => $primes[2]->toBytes(true), 'exponent1' => $exponents[1]->toBytes(true), 'exponent2' => $exponents[2]->toBytes(true), 'coefficient' => $coefficients[2]->toBytes(true));
$components = array();
foreach ($raw as $name => $value) {
$components[$name] = pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($value)), $value);
}
$RSAPrivateKey = implode('', $components);
if ($num_primes > 2) {
$OtherPrimeInfos = '';
for ($i = 3; $i <= $num_primes; $i++) {
// OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
//
// OtherPrimeInfo ::= SEQUENCE {
// prime INTEGER, -- ri
// exponent INTEGER, -- di
// coefficient INTEGER -- ti
// }
$OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
$OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
$OtherPrimeInfo .= pack('Ca*a*', self::ASN1_INTEGER, self::_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
$OtherPrimeInfos .= pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
}
$RSAPrivateKey .= pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
}
$RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, self::_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
if (!empty($password) || is_string($password)) {
$cipher = self::getEncryptionObject(self::$defaultEncryptionAlgorithm);
$iv = Random::string($cipher->getBlockLength() >> 3);
$cipher->setKey(self::generateSymmetricKey($password, $iv, $cipher->getKeyLength()));
$cipher->setIV($iv);
$iv = strtoupper(bin2hex($iv));
$RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: " . self::$defaultEncryptionAlgorithm . ",{$iv}\r\n" . "\r\n" . chunk_split(base64_encode($cipher->encrypt($RSAPrivateKey)), 64) . '-----END RSA PRIVATE KEY-----';
} else {
$RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END RSA PRIVATE KEY-----';
}
return $RSAPrivateKey;
}
示例15: createIV
/**
* Initialization
* Store the initialization vector because it will be needed for
* further decryption. I don't think necessary to have one iv
* per server so I don't put the server number in the cookie name.
*
* @return void
*/
public function createIV()
{
/* Testsuite shortcut only to allow predictable IV */
if (!is_null($this->_cookie_iv)) {
return $this->_cookie_iv;
}
if (self::useOpenSSL()) {
return openssl_random_pseudo_bytes($this->getIVSize());
} else {
return Crypt\Random::string($this->getIVSize());
}
}