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); } }
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); }
/** * 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; }
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); }
/** * 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; } }
/** * 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); }
/** * 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}"); }
/** * 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; }
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 . ');'); }
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); }
/** * 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-----"; }
/** * 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( //'authorityCertIssuer' => array( // array( // 'directoryName' => $issuer->dn // ) //), '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('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; } } if (count($ipAddresses)) { $altName = array_merge($altName, $ipAddresses); } } if (!empty($altName)) { $this->setExtension('id-ce-subjectAltName', $altName); } if ($this->caFlag) { $keyUsage = $this->getExtension('id-ce-keyUsage'); if (!$keyUsage) { $keyUsage = array(); } $this->setExtension( 'id-ce-keyUsage', array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))) ); $basicConstraints = $this->getExtension('id-ce-basicConstraints'); if (!$basicConstraints) { $basicConstraints = array(); } $this->setExtension( 'id-ce-basicConstraints', array_unique(array_merge(array('cA' => true), $basicConstraints)), true ); if (!isset($subject->currentKeyIdentifier)) { $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false); } } // resync $this->signatureSubject // save $tbsCertificate in case there are any \phpseclib\File\ASN1\Element objects in it $tbsCertificate = $this->currentCert['tbsCertificate']; $this->loadX509($this->saveX509($this->currentCert)); $result = $this->_sign($issuer->privateKey, $signatureAlgorithm); $result['tbsCertificate'] = $tbsCertificate; $this->currentCert = $currentCert; $this->signatureSubject = $signatureSubject; return $result; }
/** * 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; }
/** * 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; }
/** * 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()); } }
/** * Creates an initialization vector (IV) from a random source * * The IV is only meant to give an alternative seed to the encryption routines. This IV does not need * to be secret at all, though it can be desirable. You even can send it along with your ciphertext * without losing security. * * @param int $size * @param int $source optional * @return string * @access public */ function phpseclib_mcrypt_create_iv($size, $source = MCRYPT_DEV_URANDOM) { if ($size < 1 || $size > 0x7fffffff) { trigger_error('mcrypt_create_iv(): Cannot create an IV with a size of less than 1 or greater than 2147483647', E_USER_WARNING); return ''; } return Random::string($size); }
/** * Encrypt data. * * @param mixed $key The list of public keys used to encrypt or a list * of passphrases. * @param mixed $data The data to be PGP encrypted. * @param array $opts Additional options: * - cipher: (integer) Cipher algorithm. * - compress: (integer) Compression algorithm. * * @param Horde_Pgp_Element_Message Encrypted message. */ protected function _encrypt($key, $data, $opts) { $msg = $this->_compressMessageOb($this->_getMessageOb($data), $opts['compress']); /* Following code adapted from OpenPGP_Crypt_Symmetric::encrypt(). */ list($cipher, $key_bytes, $block_bytes) = OpenPGP_Crypt_Symmetric::getCipher($opts['cipher']); $prefix = Crypt\Random::String($block_bytes); $prefix .= substr($prefix, -2); $to_encrypt = $prefix . $msg->to_bytes(); $mdc = new OpenPGP_ModificationDetectionCodePacket(hash('sha1', $to_encrypt . "Ó", true)); /* This is the symmetric encryption session key. */ $ckey = Crypt\Random::String($key_bytes); $cipher->setKey($ckey); /* This is the symmetrically encrypted version of plaintext. */ $encrypted = array(new OpenPGP_IntegrityProtectedDataPacket($cipher->encrypt($to_encrypt . $mdc->to_bytes()))); /* Now we need to encrypt the symmetric session key into the various * session key encrypted entities. */ foreach ($key as $k) { /* Symmetric encryption. */ if (is_string($k)) { $s2k = new OpenPGP_S2K(Crypt\Random::String(8, 2)); // SHA-1 $cipher->setKey($s2k->make_key($k, $key_bytes)); $encrypted[] = new OpenPGP_SymmetricSessionKeyPacket($s2k, $cipher->encrypt(chr($opts['cipher']) . $ckey), $opts['cipher']); continue; } /* Public key encryption. */ switch ($k->algorithm) { case 1: case 2: case 3: $rsa = new OpenPGP_Crypt_RSA($k); $pk = $rsa->public_key(); $pk->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); break; case 16: $pk = new Horde_Pgp_Crypt_Elgamal($k); break; } $pk_encrypt = $pk->encrypt(chr($opts['cipher']) . $ckey . pack('n', OpenPGP_Crypt_Symmetric::checksum($ckey))); $esk = array(); foreach (is_array($pk_encrypt) ? $pk_encrypt : array($pk_encrypt) as $val) { $esk[] = pack('n', OpenPGP::bitlength($val)) . $val; } $encrypted[] = new OpenPGP_AsymmetricSessionKeyPacket($k->algorithm, $k->fingerprint(), implode('', $esk)); } return new Horde_Pgp_Element_Message(new OpenPGP_Message(array_reverse($encrypted))); }
/** * 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() { if (self::useOpenSSL()) { $this->_cookie_iv = openssl_random_pseudo_bytes($this->getIVSize()); } else { $this->_cookie_iv = Crypt\Random::string($this->getIVSize()); } $GLOBALS['PMA_Config']->setCookie('pma_iv-' . $GLOBALS['server'], base64_encode($this->_cookie_iv)); }
private function generateRandomBytes($length) { return Random::string($length); }
/** * @param int $length * * @throws \Exception * * @return string */ private function generateRandomString($length) { if (function_exists('random_bytes')) { return random_bytes($length); } elseif (function_exists('mcrypt_create_iv')) { return mcrypt_create_iv($length); } elseif (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($length); } elseif (class_exists('\\phpseclib\\Crypt\\Random')) { return \phpseclib\Crypt\Random::string($length); } else { throw new \Exception('Unable to create a random string'); } }
/** * Wrap a private key appropriately * * @access public * @param string $key * @param string $type * @param string $password * @return string */ static function wrapPrivateKey($key, $type, $password) { if (empty($password) || !is_string($password)) { return "-----BEGIN {$type} PRIVATE KEY-----\r\n" . chunk_split(Base64::encode($key), 64) . "-----END {$type} PRIVATE KEY-----"; } $cipher = self::getEncryptionObject(self::$defaultEncryptionAlgorithm); $iv = Random::string($cipher->getBlockLength() >> 3); $cipher->setKey(self::generateSymmetricKey($password, $iv, $cipher->getKeyLength() >> 3)); $cipher->setIV($iv); $iv = strtoupper(Hex::encode($iv)); return "-----BEGIN {$type} 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($key)), 64) . "-----END {$type} PRIVATE KEY-----"; }
/** * 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 \phpseclib\Net\SSH1::__construct() * @param BigInteger $m * @param Array $key * @return BigInteger * @access private */ function _rsa_crypt($m, $key) { /* $rsa = new RSA(); $rsa->loadKey($key, RSA::PUBLIC_FORMAT_RAW); $rsa->setEncryptionMode(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 = Random::string($length - strlen($random)); $block = str_replace("", '', $block); $random .= $block; } $temp = chr(0) . chr(2) . $random . chr(0) . $m; $m = new BigInteger($temp, 256); $m = $m->modPow($key[0], $key[1]); return $m->toBytes(); }
/** * @param RedisMailJob|MailJobInterface $mailJob * * @return string */ protected function createPayload(MailJobInterface $mailJob) { return json_encode(['id' => $mailJob->isNewRecord() ? sha1(Random::string(32)) : $mailJob->getId(), 'attempt' => $mailJob->getAttempt(), 'message' => $mailJob->getMessage()]); }
/** * Generates a random BigInteger * * Byte length is equal to $length. Uses Crypt\Random if it's loaded and mt_rand if it's not. * * @param Integer $length * @return \PHPSecLib\Math\BigInteger * @access private */ function _random_number_helper($size) { if (class_exists('phpseclib\\Crypt\\Random')) { $random = Random::string($size); } else { $random = ''; if ($size & 1) { $random .= chr(mt_rand(0, 255)); } $blocks = $size >> 1; for ($i = 0; $i < $blocks; ++$i) { // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems $random .= pack('n', mt_rand(0, 0xffff)); } } return new static($random, 256); }
/** * EMSA-PSS-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. * * @access private * @param string $m * @param int $emBits */ function _emsa_pss_encode($m, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) $sLen = $this->sLen ? $this->sLen : $this->hLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { user_error('Encoding error'); return false; } $salt = Random::string($sLen); $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h = $this->hash->hash($m2); $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2); $db = $ps . chr(1) . $salt; $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0]; $em = $maskedDB . $h . chr(0xBC); return $em; }
/** * Sends Binary Packets * * See '6. Binary Packet Protocol' of rfc4253 for more info. * * @param String $data * @param optional String $logged * @see \phpseclib\Net\SSH2::_get_binary_packet() * @return Boolean * @access private */ function _send_binary_packet($data, $logged = null) { if (!is_resource($this->fsock) || feof($this->fsock)) { user_error('Connection closed prematurely'); $this->bitmap = 0; return false; } //if ($this->compress) { // // the -4 removes the checksum: // // http://php.net/function.gzcompress#57710 // $data = substr(gzcompress($data), 0, -4); //} // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9 $packet_length = strlen($data) + 9; // round up to the nearest $this->encrypt_block_size $packet_length += ($this->encrypt_block_size - 1) * $packet_length % $this->encrypt_block_size; // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length $padding_length = $packet_length - strlen($data) - 5; $padding = Random::string($padding_length); // we subtract 4 from packet_length because the packet_length field isn't supposed to include itself $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding); $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : ''; $this->send_seq_no++; if ($this->encrypt !== false) { $packet = $this->encrypt->encrypt($packet); } $packet .= $hmac; $start = microtime(true); $result = strlen($packet) == fputs($this->fsock, $packet); $stop = microtime(true); if (defined('NET_SSH2_LOGGING')) { $current = microtime(true); $message_number = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')'; $message_number = '-> ' . $message_number . ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)'; $this->_append_log($message_number, isset($logged) ? $logged : $data); $this->last_packet = $current; } return $result; }
/** * Generate a random large number. * * @return int */ public static function generateRandomInteger() { return (int) hexdec(bin2hex(Random::string(4))) & Optimus::MAX_INT; }