/vendor/phpseclib/phpseclib/phpseclib/Crypt/RSA.php
PHP | 3037 lines | 1627 code | 297 blank | 1113 comment | 266 complexity | e97a99b790eecd75f3fb5edb5cb6a951 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
- *
- * PHP version 5
- *
- * Here's an example of how to encrypt and decrypt text with this library:
- * <code>
- * <?php
- * include 'vendor/autoload.php';
- *
- * $rsa = new \phpseclib\Crypt\RSA();
- * extract($rsa->createKey());
- *
- * $plaintext = 'terrafrost';
- *
- * $rsa->loadKey($privatekey);
- * $ciphertext = $rsa->encrypt($plaintext);
- *
- * $rsa->loadKey($publickey);
- * echo $rsa->decrypt($ciphertext);
- * ?>
- * </code>
- *
- * Here's an example of how to create signatures and verify signatures with this library:
- * <code>
- * <?php
- * include 'vendor/autoload.php';
- *
- * $rsa = new \phpseclib\Crypt\RSA();
- * extract($rsa->createKey());
- *
- * $plaintext = 'terrafrost';
- *
- * $rsa->loadKey($privatekey);
- * $signature = $rsa->sign($plaintext);
- *
- * $rsa->loadKey($publickey);
- * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
- * ?>
- * </code>
- *
- * @category Crypt
- * @package RSA
- * @author Jim Wigginton <terrafrost@php.net>
- * @copyright 2009 Jim Wigginton
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
- * @link http://phpseclib.sourceforge.net
- */
- namespace phpseclib\Crypt;
- use phpseclib\Math\BigInteger;
- /**
- * Pure-PHP PKCS#1 compliant implementation of RSA.
- *
- * @package RSA
- * @author Jim Wigginton <terrafrost@php.net>
- * @access public
- */
- class RSA
- {
- /**#@+
- * @access public
- * @see self::encrypt()
- * @see self::decrypt()
- */
- /**
- * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
- * (OAEP) for encryption / decryption.
- *
- * Uses sha1 by default.
- *
- * @see self::setHash()
- * @see self::setMGFHash()
- */
- const ENCRYPTION_OAEP = 1;
- /**
- * Use PKCS#1 padding.
- *
- * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
- * compatibility with protocols (like SSH-1) written before OAEP's introduction.
- */
- const ENCRYPTION_PKCS1 = 2;
- /**
- * Do not use any padding
- *
- * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
- * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
- */
- const ENCRYPTION_NONE = 3;
- /**#@-*/
- /**#@+
- * @access public
- * @see self::sign()
- * @see self::verify()
- * @see self::setHash()
- */
- /**
- * Use the Probabilistic Signature Scheme for signing
- *
- * Uses sha1 by default.
- *
- * @see self::setSaltLength()
- * @see self::setMGFHash()
- */
- const SIGNATURE_PSS = 1;
- /**
- * Use the PKCS#1 scheme by default.
- *
- * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
- * compatibility with protocols (like SSH-2) written before PSS's introduction.
- */
- const SIGNATURE_PKCS1 = 2;
- /**#@-*/
- /**#@+
- * @access private
- * @see \phpseclib\Crypt\RSA::createKey()
- */
- /**
- * ASN1 Integer
- */
- const ASN1_INTEGER = 2;
- /**
- * ASN1 Bit String
- */
- const ASN1_BITSTRING = 3;
- /**
- * ASN1 Octet String
- */
- const ASN1_OCTETSTRING = 4;
- /**
- * ASN1 Object Identifier
- */
- const ASN1_OBJECT = 6;
- /**
- * ASN1 Sequence (with the constucted bit set)
- */
- const ASN1_SEQUENCE = 48;
- /**#@-*/
- /**#@+
- * @access private
- * @see \phpseclib\Crypt\RSA::__construct()
- */
- /**
- * To use the pure-PHP implementation
- */
- const MODE_INTERNAL = 1;
- /**
- * To use the OpenSSL library
- *
- * (if enabled; otherwise, the internal implementation will be used)
- */
- const MODE_OPENSSL = 2;
- /**#@-*/
- /**#@+
- * @access public
- * @see \phpseclib\Crypt\RSA::createKey()
- * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat()
- */
- /**
- * PKCS#1 formatted private key
- *
- * Used by OpenSSH
- */
- const PRIVATE_FORMAT_PKCS1 = 0;
- /**
- * PuTTY formatted private key
- */
- const PRIVATE_FORMAT_PUTTY = 1;
- /**
- * XML formatted private key
- */
- const PRIVATE_FORMAT_XML = 2;
- /**
- * PKCS#8 formatted private key
- */
- const PRIVATE_FORMAT_PKCS8 = 8;
- /**#@-*/
- /**#@+
- * @access public
- * @see \phpseclib\Crypt\RSA::createKey()
- * @see \phpseclib\Crypt\RSA::setPublicKeyFormat()
- */
- /**
- * Raw public key
- *
- * An array containing two \phpseclib\Math\BigInteger objects.
- *
- * The exponent can be indexed with any of the following:
- *
- * 0, e, exponent, publicExponent
- *
- * The modulus can be indexed with any of the following:
- *
- * 1, n, modulo, modulus
- */
- const PUBLIC_FORMAT_RAW = 3;
- /**
- * PKCS#1 formatted public key (raw)
- *
- * Used by File/X509.php
- *
- * Has the following header:
- *
- * -----BEGIN RSA PUBLIC KEY-----
- *
- * Analogous to ssh-keygen's pem format (as specified by -m)
- */
- const PUBLIC_FORMAT_PKCS1 = 4;
- const PUBLIC_FORMAT_PKCS1_RAW = 4;
- /**
- * XML formatted public key
- */
- const PUBLIC_FORMAT_XML = 5;
- /**
- * OpenSSH formatted public key
- *
- * Place in $HOME/.ssh/authorized_keys
- */
- const PUBLIC_FORMAT_OPENSSH = 6;
- /**
- * PKCS#1 formatted public key (encapsulated)
- *
- * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
- *
- * Has the following header:
- *
- * -----BEGIN PUBLIC KEY-----
- *
- * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
- * is specific to private keys it's basically creating a DER-encoded wrapper
- * for keys. This just extends that same concept to public keys (much like ssh-keygen)
- */
- const PUBLIC_FORMAT_PKCS8 = 7;
- /**#@-*/
- /**
- * Precomputed Zero
- *
- * @var array
- * @access private
- */
- var $zero;
- /**
- * Precomputed One
- *
- * @var array
- * @access private
- */
- var $one;
- /**
- * Private Key Format
- *
- * @var int
- * @access private
- */
- var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
- /**
- * Public Key Format
- *
- * @var int
- * @access public
- */
- var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
- /**
- * Modulus (ie. n)
- *
- * @var \phpseclib\Math\BigInteger
- * @access private
- */
- var $modulus;
- /**
- * Modulus length
- *
- * @var \phpseclib\Math\BigInteger
- * @access private
- */
- var $k;
- /**
- * Exponent (ie. e or d)
- *
- * @var \phpseclib\Math\BigInteger
- * @access private
- */
- var $exponent;
- /**
- * Primes for Chinese Remainder Theorem (ie. p and q)
- *
- * @var array
- * @access private
- */
- var $primes;
- /**
- * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
- *
- * @var array
- * @access private
- */
- var $exponents;
- /**
- * Coefficients for Chinese Remainder Theorem (ie. qInv)
- *
- * @var array
- * @access private
- */
- var $coefficients;
- /**
- * Hash name
- *
- * @var string
- * @access private
- */
- var $hashName;
- /**
- * Hash function
- *
- * @var \phpseclib\Crypt\Hash
- * @access private
- */
- var $hash;
- /**
- * Length of hash function output
- *
- * @var int
- * @access private
- */
- var $hLen;
- /**
- * Length of salt
- *
- * @var int
- * @access private
- */
- var $sLen;
- /**
- * Hash function for the Mask Generation Function
- *
- * @var \phpseclib\Crypt\Hash
- * @access private
- */
- var $mgfHash;
- /**
- * Length of MGF hash function output
- *
- * @var int
- * @access private
- */
- var $mgfHLen;
- /**
- * Encryption mode
- *
- * @var int
- * @access private
- */
- var $encryptionMode = self::ENCRYPTION_OAEP;
- /**
- * Signature mode
- *
- * @var int
- * @access private
- */
- var $signatureMode = self::SIGNATURE_PSS;
- /**
- * Public Exponent
- *
- * @var mixed
- * @access private
- */
- var $publicExponent = false;
- /**
- * Password
- *
- * @var string
- * @access private
- */
- var $password = false;
- /**
- * Components
- *
- * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
- * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
- *
- * @see self::_start_element_handler()
- * @var array
- * @access private
- */
- var $components = array();
- /**
- * Current String
- *
- * For use with parsing XML formatted keys.
- *
- * @see self::_character_handler()
- * @see self::_stop_element_handler()
- * @var mixed
- * @access private
- */
- var $current;
- /**
- * OpenSSL configuration file name.
- *
- * Set to null to use system configuration file.
- * @see self::createKey()
- * @var mixed
- * @Access public
- */
- var $configFile;
- /**
- * Public key comment field.
- *
- * @var string
- * @access private
- */
- var $comment = 'phpseclib-generated-key';
- /**
- * The constructor
- *
- * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
- * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
- * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
- *
- * @return \phpseclib\Crypt\RSA
- * @access public
- */
- function __construct()
- {
- $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
- if (!defined('CRYPT_RSA_MODE')) {
- switch (true) {
- // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
- // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
- // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
- case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- break;
- case extension_loaded('openssl') && file_exists($this->configFile):
- // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
- ob_start();
- @phpinfo();
- $content = ob_get_contents();
- ob_end_clean();
- preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
- $versions = array();
- if (!empty($matches[1])) {
- for ($i = 0; $i < count($matches[1]); $i++) {
- $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
- // Remove letter part in OpenSSL version
- if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) {
- $versions[$matches[1][$i]] = $fullVersion;
- } else {
- $versions[$matches[1][$i]] = $m[0];
- }
- }
- }
- // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
- switch (true) {
- case !isset($versions['Header']):
- case !isset($versions['Library']):
- case $versions['Header'] == $versions['Library']:
- define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
- break;
- default:
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
- }
- break;
- default:
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- }
- }
- $this->zero = new BigInteger();
- $this->one = new BigInteger(1);
- $this->hash = new Hash('sha1');
- $this->hLen = $this->hash->getLength();
- $this->hashName = 'sha1';
- $this->mgfHash = new Hash('sha1');
- $this->mgfHLen = $this->mgfHash->getLength();
- }
- /**
- * Create public / private key pair
- *
- * Returns an array with the following three elements:
- * - 'privatekey': The private key.
- * - 'publickey': The public key.
- * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
- * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.
- *
- * @access public
- * @param int $bits
- * @param int $timeout
- * @param array $p
- */
- function createKey($bits = 1024, $timeout = false, $partial = array())
- {
- if (!defined('CRYPT_RSA_EXPONENT')) {
- // http://en.wikipedia.org/wiki/65537_%28number%29
- define('CRYPT_RSA_EXPONENT', '65537');
- }
- // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
- // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
- // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
- // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then
- // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
- // generation when there's a chance neither gmp nor OpenSSL are installed)
- if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
- define('CRYPT_RSA_SMALLEST_PRIME', 4096);
- }
- // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
- if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
- $config = array();
- if (isset($this->configFile)) {
- $config['config'] = $this->configFile;
- }
- $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
- openssl_pkey_export($rsa, $privatekey, null, $config);
- $publickey = openssl_pkey_get_details($rsa);
- $publickey = $publickey['key'];
- $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1)));
- $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1)));
- // clear the buffer of error strings stemming from a minimalistic openssl.cnf
- while (openssl_error_string() !== false) {
- }
- return array(
- 'privatekey' => $privatekey,
- 'publickey' => $publickey,
- 'partialkey' => false
- );
- }
- static $e;
- if (!isset($e)) {
- $e = new BigInteger(CRYPT_RSA_EXPONENT);
- }
- extract($this->_generateMinMax($bits));
- $absoluteMin = $min;
- $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
- if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
- $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
- $temp = CRYPT_RSA_SMALLEST_PRIME;
- } else {
- $num_primes = 2;
- }
- extract($this->_generateMinMax($temp + $bits % $temp));
- $finalMax = $max;
- extract($this->_generateMinMax($temp));
- $generator = new BigInteger();
- $n = $this->one->copy();
- if (!empty($partial)) {
- extract(unserialize($partial));
- } else {
- $exponents = $coefficients = $primes = array();
- $lcm = array(
- 'top' => $this->one->copy(),
- 'bottom' => false
- );
- }
- $start = time();
- $i0 = count($primes) + 1;
- do {
- for ($i = $i0; $i <= $num_primes; $i++) {
- if ($timeout !== false) {
- $timeout-= time() - $start;
- $start = time();
- if ($timeout <= 0) {
- return array(
- 'privatekey' => '',
- 'publickey' => '',
- 'partialkey' => serialize(array(
- 'primes' => $primes,
- 'coefficients' => $coefficients,
- 'lcm' => $lcm,
- 'exponents' => $exponents
- ))
- );
- }
- }
- if ($i == $num_primes) {
- list($min, $temp) = $absoluteMin->divide($n);
- if (!$temp->equals($this->zero)) {
- $min = $min->add($this->one); // ie. ceil()
- }
- $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
- } else {
- $primes[$i] = $generator->randomPrime($min, $max, $timeout);
- }
- if ($primes[$i] === false) { // if we've reached the timeout
- if (count($primes) > 1) {
- $partialkey = '';
- } else {
- array_pop($primes);
- $partialkey = serialize(array(
- 'primes' => $primes,
- 'coefficients' => $coefficients,
- 'lcm' => $lcm,
- 'exponents' => $exponents
- ));
- }
- return array(
- 'privatekey' => '',
- 'publickey' => '',
- 'partialkey' => $partialkey
- );
- }
- // the first coefficient is calculated differently from the rest
- // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
- if ($i > 2) {
- $coefficients[$i] = $n->modInverse($primes[$i]);
- }
- $n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract($this->one);
- // textbook RSA implementations use Euler's totient function instead of the least common multiple.
- // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
- $lcm['top'] = $lcm['top']->multiply($temp);
- $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
- $exponents[$i] = $e->modInverse($temp);
- }
- list($temp) = $lcm['top']->divide($lcm['bottom']);
- $gcd = $temp->gcd($e);
- $i0 = 1;
- } while (!$gcd->equals($this->one));
- $d = $e->modInverse($temp);
- $coefficients[2] = $primes[2]->modInverse($primes[1]);
- // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
- // RSAPrivateKey ::= SEQUENCE {
- // version Version,
- // modulus INTEGER, -- n
- // publicExponent INTEGER, -- e
- // privateExponent INTEGER, -- d
- // prime1 INTEGER, -- p
- // prime2 INTEGER, -- q
- // exponent1 INTEGER, -- d mod (p-1)
- // exponent2 INTEGER, -- d mod (q-1)
- // coefficient INTEGER, -- (inverse of q) mod p
- // otherPrimeInfos OtherPrimeInfos OPTIONAL
- // }
- return array(
- 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
- 'publickey' => $this->_convertPublicKey($n, $e),
- 'partialkey' => false
- );
- }
- /**
- * Convert a private key to the appropriate format.
- *
- * @access private
- * @see self::setPrivateKeyFormat()
- * @param string $RSAPrivateKey
- * @return string
- */
- function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
- {
- $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML;
- $num_primes = count($primes);
- $raw = array(
- 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
- 'modulus' => $n->toBytes($signed),
- 'publicExponent' => $e->toBytes($signed),
- 'privateExponent' => $d->toBytes($signed),
- 'prime1' => $primes[1]->toBytes($signed),
- 'prime2' => $primes[2]->toBytes($signed),
- 'exponent1' => $exponents[1]->toBytes($signed),
- 'exponent2' => $exponents[2]->toBytes($signed),
- 'coefficient' => $coefficients[2]->toBytes($signed)
- );
- // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
- // call _convertPublicKey() instead.
- switch ($this->privateKeyFormat) {
- case self::PRIVATE_FORMAT_XML:
- if ($num_primes != 2) {
- return false;
- }
- return "<RSAKeyValue>\r\n" .
- ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
- ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
- ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
- ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
- ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
- ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
- ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
- ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
- '</RSAKeyValue>';
- break;
- case self::PRIVATE_FORMAT_PUTTY:
- if ($num_primes != 2) {
- return false;
- }
- $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
- $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
- $key.= $encryption;
- $key.= "\r\nComment: " . $this->comment . "\r\n";
- $public = pack(
- 'Na*Na*Na*',
- strlen('ssh-rsa'),
- 'ssh-rsa',
- strlen($raw['publicExponent']),
- $raw['publicExponent'],
- strlen($raw['modulus']),
- $raw['modulus']
- );
- $source = pack(
- 'Na*Na*Na*Na*',
- strlen('ssh-rsa'),
- 'ssh-rsa',
- strlen($encryption),
- $encryption,
- strlen($this->comment),
- $this->comment,
- strlen($public),
- $public
- );
- $public = base64_encode($public);
- $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
- $key.= chunk_split($public, 64);
- $private = pack(
- 'Na*Na*Na*Na*',
- strlen($raw['privateExponent']),
- $raw['privateExponent'],
- strlen($raw['prime1']),
- $raw['prime1'],
- strlen($raw['prime2']),
- $raw['prime2'],
- strlen($raw['coefficient']),
- $raw['coefficient']
- );
- if (empty($this->password) && !is_string($this->password)) {
- $source.= pack('Na*', strlen($private), $private);
- $hashkey = 'putty-private-key-file-mac-key';
- } else {
- $private.= Random::string(16 - (strlen($private) & 15));
- $source.= pack('Na*', strlen($private), $private);
- $sequence = 0;
- $symkey = '';
- while (strlen($symkey) < 32) {
- $temp = pack('Na*', $sequence++, $this->password);
- $symkey.= pack('H*', sha1($temp));
- }
- $symkey = substr($symkey, 0, 32);
- $crypto = new AES();
- $crypto->setKey($symkey);
- $crypto->disablePadding();
- $private = $crypto->encrypt($private);
- $hashkey = 'putty-private-key-file-mac-key' . $this->password;
- }
- $private = base64_encode($private);
- $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
- $key.= chunk_split($private, 64);
- $hash = new Hash('sha1');
- $hash->setKey(pack('H*', sha1($hashkey)));
- $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
- return $key;
- default: // eg. self::PRIVATE_FORMAT_PKCS1
- $components = array();
- foreach ($raw as $name => $value) {
- $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_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, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
- $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
- $OtherPrimeInfos.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
- }
- $RSAPrivateKey.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
- }
- $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
- if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) {
- $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
- $RSAPrivateKey = pack(
- 'Ca*a*Ca*a*',
- self::ASN1_INTEGER,
- "\01\00",
- $rsaOID,
- 4,
- $this->_encodeLength(strlen($RSAPrivateKey)),
- $RSAPrivateKey
- );
- $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
- if (!empty($this->password) || is_string($this->password)) {
- $salt = Random::string(8);
- $iterationCount = 2048;
- $crypto = new DES();
- $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
- $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
- $parameters = pack(
- 'Ca*a*Ca*N',
- self::ASN1_OCTETSTRING,
- $this->_encodeLength(strlen($salt)),
- $salt,
- self::ASN1_INTEGER,
- $this->_encodeLength(4),
- $iterationCount
- );
- $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
- $encryptionAlgorithm = pack(
- 'Ca*a*Ca*a*',
- self::ASN1_OBJECT,
- $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)),
- $pbeWithMD5AndDES_CBC,
- self::ASN1_SEQUENCE,
- $this->_encodeLength(strlen($parameters)),
- $parameters
- );
- $RSAPrivateKey = pack(
- 'Ca*a*Ca*a*',
- self::ASN1_SEQUENCE,
- $this->_encodeLength(strlen($encryptionAlgorithm)),
- $encryptionAlgorithm,
- self::ASN1_OCTETSTRING,
- $this->_encodeLength(strlen($RSAPrivateKey)),
- $RSAPrivateKey
- );
- $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_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;
- }
- if (!empty($this->password) || is_string($this->password)) {
- $iv = Random::string(8);
- $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
- $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
- $des = new TripleDES();
- $des->setKey($symkey);
- $des->setIV($iv);
- $iv = strtoupper(bin2hex($iv));
- $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
- "Proc-Type: 4,ENCRYPTED\r\n" .
- "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
- "\r\n" .
- chunk_split(base64_encode($des->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;
- }
- }
- /**
- * Convert a public key to the appropriate format
- *
- * @access private
- * @see self::setPublicKeyFormat()
- * @param string $RSAPrivateKey
- * @return string
- */
- function _convertPublicKey($n, $e)
- {
- $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML;
- $modulus = $n->toBytes($signed);
- $publicExponent = $e->toBytes($signed);
- switch ($this->publicKeyFormat) {
- case self::PUBLIC_FORMAT_RAW:
- return array('e' => $e->copy(), 'n' => $n->copy());
- case self::PUBLIC_FORMAT_XML:
- return "<RSAKeyValue>\r\n" .
- ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
- ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
- '</RSAKeyValue>';
- break;
- case self::PUBLIC_FORMAT_OPENSSH:
- // from <http://tools.ietf.org/html/rfc4253#page-15>:
- // string "ssh-rsa"
- // mpint e
- // mpint n
- $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
- $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
- return $RSAPublicKey;
- default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1
- // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
- // RSAPublicKey ::= SEQUENCE {
- // modulus INTEGER, -- n
- // publicExponent INTEGER -- e
- // }
- $components = array(
- 'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
- 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
- );
- $RSAPublicKey = pack(
- 'Ca*a*a*',
- self::ASN1_SEQUENCE,
- $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
- $components['modulus'],
- $components['publicExponent']
- );
- if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) {
- $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
- chunk_split(base64_encode($RSAPublicKey), 64) .
- '-----END RSA PUBLIC KEY-----';
- } else {
- // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
- $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
- $RSAPublicKey = chr(0) . $RSAPublicKey;
- $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
- $RSAPublicKey = pack(
- 'Ca*a*',
- self::ASN1_SEQUENCE,
- $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
- $rsaOID . $RSAPublicKey
- );
- $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
- chunk_split(base64_encode($RSAPublicKey), 64) .
- '-----END PUBLIC KEY-----';
- }
- return $RSAPublicKey;
- }
- }
- /**
- * Break a public or private key down into its constituant components
- *
- * @access private
- * @see self::_convertPublicKey()
- * @see self::_convertPrivateKey()
- * @param string $key
- * @param int $type
- * @return array
- */
- function _parseKey($key, $type)
- {
- if ($type != self::PUBLIC_FORMAT_RAW && !is_string($key)) {
- return false;
- }
- switch ($type) {
- case self::PUBLIC_FORMAT_RAW:
- if (!is_array($key)) {
- return false;
- }
- $components = array();
- switch (true) {
- case isset($key['e']):
- $components['publicExponent'] = $key['e']->copy();
- break;
- case isset($key['exponent']):
- $components['publicExponent'] = $key['exponent']->copy();
- break;
- case isset($key['publicExponent']):
- $components['publicExponent'] = $key['publicExponent']->copy();
- break;
- case isset($key[0]):
- $components['publicExponent'] = $key[0]->copy();
- }
- switch (true) {
- case isset($key['n']):
- $components['modulus'] = $key['n']->copy();
- break;
- case isset($key['modulo']):
- $components['modulus'] = $key['modulo']->copy();
- break;
- case isset($key['modulus']):
- $components['modulus'] = $key['modulus']->copy();
- break;
- case isset($key[1]):
- $components['modulus'] = $key[1]->copy();
- }
- return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
- case self::PRIVATE_FORMAT_PKCS1:
- case self::PRIVATE_FORMAT_PKCS8:
- case self::PUBLIC_FORMAT_PKCS1:
- /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
- "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
- protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
- two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
- http://tools.ietf.org/html/rfc1421#section-4.6.1.1
- http://tools.ietf.org/html/rfc1421#section-4.6.1.3
- DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
- DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
- function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
- own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
- implementation are part of the standard, as well.
- * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
- if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
- $iv = pack('H*', trim($matches[2]));
- $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
- $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
- // remove the Proc-Type / DEK-Info sections as they're no longer needed
- $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
- $ciphertext = $this->_extractBER($key);
- if ($ciphertext === false) {
- $ciphertext = $key;
- }
- switch ($matches[1]) {
- case 'AES-256-CBC':
- $crypto = new AES();
- break;
- case 'AES-128-CBC':
- $symkey = substr($symkey, 0, 16);
- $crypto = new AES();
- break;
- case 'DES-EDE3-CFB':
- $crypto = new TripleDES(Base::MODE_CFB);
- break;
- case 'DES-EDE3-CBC':
- $symkey = substr($symkey, 0, 24);
- $crypto = new TripleDES();
- break;
- case 'DES-CBC':
- $crypto = new DES();
- break;
- default:
- return false;
- }
- $crypto->setKey($symkey);
- $crypto->setIV($iv);
- $decoded = $crypto->decrypt($ciphertext);
- } else {
- $decoded = $this->_extractBER($key);
- }
- if ($decoded !== false) {
- $key = $decoded;
- }
- $components = array();
- if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
- return false;
- }
- if ($this->_decodeLength($key) != strlen($key)) {
- return false;
- }
- $tag = ord($this->_string_shift($key));
- /* intended for keys for which OpenSSL's asn1parse returns the following:
- 0:d=0 hl=4 l= 631 cons: SEQUENCE
- 4:d=1 hl=2 l= 1 prim: INTEGER :00
- 7:d=1 hl=2 l= 13 cons: SEQUENCE
- 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
- 20:d=2 hl=2 l= 0 prim: NULL
- 22:d=1 hl=4 l= 609 prim: OCTET STRING
- ie. PKCS8 keys*/
- if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
- $this->_string_shift($key, 3);
- $tag = self::ASN1_SEQUENCE;
- }
- if ($tag == self::ASN1_SEQUENCE) {
- $temp = $this->_string_shift($key, $this->_decodeLength($key));
- if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) {
- return false;
- }
- $length = $this->_decodeLength($temp);
- switch ($this->_string_shift($temp, $length)) {
- case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption
- break;
- case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC
- /*
- PBEParameter ::= SEQUENCE {
- salt OCTET STRING (SIZE(8)),
- iterationCount INTEGER }
- */
- if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) {
- return false;
- }
- if ($this->_decodeLength($temp) != strlen($temp)) {
- return false;
- }
- $this->_string_shift($temp); // assume it's an octet string
- $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
- if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) {
- return false;
- }
- $this->_decodeLength($temp);
- list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
- $this->_string_shift($key); // assume it's an octet string
- $length = $this->_decodeLength($key);
- if (strlen($key) != $length) {
- return false;
- }
- $crypto = new DES();
- $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
- $key = $crypto->decrypt($key);
- if ($key === false) {
- return false;
- }
- return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1);
- default:
- return false;
- }
- /* intended for keys for which OpenSSL's asn1parse returns the following:
- 0:d=0 hl=4 l= 290 cons: SEQUENCE
- 4:d=1 hl=2 l= 13 cons: SEQUENCE
- 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
- 17:d=2 hl=2 l= 0 prim: NULL
- 19:d=1 hl=4 l= 271 prim: BIT STRING */
- $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
- $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
- // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
- // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
- // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
- if ($tag == self::ASN1_BITSTRING) {
- $this->_string_shift($key);
- }
- if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
- return false;
- }
- if ($this->_decodeLength($key) != strlen($key)) {
- return false;
- }
- $tag = ord($this->_string_shift($key));
- }
- if ($tag != self::ASN1_INTEGER) {
- return false;
- }
- $length = $this->_decodeLength($key);
- $temp = $this->_string_shift($key, $length);
- if (strlen($temp) != 1 || ord($temp) > 2) {
- $components['modulus'] = new BigInteger($temp, 256);
- $this->_string_shift($key); // skip over self::ASN1_INTEGER
- $length = $this->_decodeLength($key);
- $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
- return $components;
- }
- if (ord($this->_string_shift($key)) != self::ASN1_INTEGER) {
- return false;
- }
- $length = $this->_decodeLength($key);
- $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256));
- if (!empty($key)) {
- if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
- return false;
- }
- $this->_decodeLength($key);
- while (!empty($key)) {
- if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
- return false;
- }
- $this->_decodeLength($key);
- $key = substr($key, 1);
- $length = $this->_decodeLength($key);
- $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
- $this->_string_shift($key);
- $length = $this->_decodeLength($key);
- $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256);
- …
Large files files are truncated, but you can click here to view the full file