* createKey());
+ * extract(\phpseclib\Crypt\RSA::::createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $rsa->loadKey($privatekey);
- * $ciphertext = $rsa->encrypt($plaintext);
+ * $ciphertext = $publickey->encrypt($plaintext);
*
- * $rsa->loadKey($publickey);
- * echo $rsa->decrypt($ciphertext);
+ * echo $privatekey->decrypt($ciphertext);
* ?>
*
*
* Here's an example of how to create signatures and verify signatures with this library:
*
* createKey());
+ * extract(\phpseclib\Crypt\RSA::createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $rsa->loadKey($privatekey);
- * $signature = $rsa->sign($plaintext);
+ * $rsa->loadKey($privatekey);
+ * $signature = $rsa->sign($plaintext);
*
- * $rsa->loadKey($publickey);
- * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
+ * $rsa->loadKey($publickey);
+ * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
* ?>
*
*
@@ -51,13 +47,8 @@
namespace phpseclib\Crypt;
-use phpseclib\Crypt\AES;
-use phpseclib\Crypt\Base;
-use phpseclib\Crypt\DES;
use phpseclib\Crypt\Hash;
use phpseclib\Crypt\Random;
-use phpseclib\Crypt\RSA;
-use phpseclib\Crypt\TripleDES;
use phpseclib\Math\BigInteger;
/**
@@ -105,7 +96,7 @@ class RSA
* @see \phpseclib\Crypt\RSA::sign()
* @see \phpseclib\Crypt\RSA::verify()
* @see \phpseclib\Crypt\RSA::setHash()
- */
+ */
/**
* Use the Probabilistic Signature Scheme for signing
*
@@ -127,7 +118,7 @@ class RSA
/**#@+
* @access private
* @see \phpseclib\Crypt\RSA::createKey()
- */
+ */
/**
* ASN1 Integer
*/
@@ -153,7 +144,7 @@ class RSA
/**#@+
* @access private
* @see \phpseclib\Crypt\RSA::__construct()
- */
+ */
/**
* To use the pure-PHP implementation
*/
@@ -166,96 +157,13 @@ class RSA
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 = 3;
- /**#@-*/
-
- /**#@+
- * @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;
+ static $zero;
/**
* Precomputed One
@@ -263,23 +171,23 @@ class RSA
* @var array
* @access private
*/
- var $one;
+ static $one;
/**
* Private Key Format
*
- * @var int
+ * @var string
* @access private
*/
- var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
+ var $privateKeyFormat = 'PKCS1';
/**
* Public Key Format
*
- * @var int
- * @access public
+ * @var string
+ * @access private
*/
- var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
+ var $publicKeyFormat = 'PKCS8';
/**
* Modulus (ie. n)
@@ -409,47 +317,39 @@ class RSA
*/
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 \phpseclib\Crypt\RSA::_start_element_handler()
- * @var array
- * @access private
- */
- var $components = array();
-
- /**
- * Current String
- *
- * For use with parsing XML formatted keys.
- *
- * @see \phpseclib\Crypt\RSA::_character_handler()
- * @see \phpseclib\Crypt\RSA::_stop_element_handler()
- * @var mixed
- * @access private
- */
- var $current;
-
/**
* OpenSSL configuration file name.
*
* Set to null to use system configuration file.
+ *
* @see \phpseclib\Crypt\RSA::createKey()
* @var mixed
- * @Access public
+ * @access public
*/
- var $configFile;
+ static $configFile;
/**
- * Public key comment field.
+ * Supported file formats
*
- * @var string
+ * @see \phpseclib\Crypt\RSA::load()
+ * @var array
* @access private
*/
- var $comment = 'phpseclib-generated-key';
+ static $fileFormats = false;
+
+ /**
+ * Initialize static variables
+ *
+ * @access private
+ */
+ static function _initialize_static_variables()
+ {
+ if (!isset(self::$zero)) {
+ self::$zero= new BigInteger(0);
+ self::$one = new BigInteger(1);
+ self::$configFile = __DIR__ . '/../openssl.cnf';
+ }
+ }
/**
* The constructor
@@ -463,7 +363,32 @@ class RSA
*/
function __construct()
{
- $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
+ self::_initialize_static_variables();
+
+ $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
+ */
+ static function createKey($bits = 1024, $timeout = false, $partial = array())
+ {
+ self::_initialize_static_variables();
if (!defined('CRYPT_RSA_MODE')) {
switch (true) {
@@ -473,7 +398,7 @@ class RSA
case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
break;
- case extension_loaded('openssl') && file_exists($this->configFile):
+ case extension_loaded('openssl') && file_exists(self::$configFile):
// some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
ob_start();
@phpinfo();
@@ -513,32 +438,6 @@ class RSA
}
}
- $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');
@@ -556,16 +455,17 @@ class RSA
// 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;
+ if (isset(self::$configFile)) {
+ $config['config'] = self::$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'];
+ openssl_pkey_export($rsa, $privatekeystr, null, $config);
+ $privatekey = new RSA();
+ $privatekey->load($privatekeystr);
- $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)));
+ $publickeyarr = openssl_pkey_get_details($rsa);
+ $publickey = new RSA();
+ $publickey->load($publickeyarr['key']);
// clear the buffer of error strings stemming from a minimalistic openssl.cnf
while (openssl_error_string() !== false) {
@@ -583,7 +483,7 @@ class RSA
$e = new BigInteger(CRYPT_RSA_EXPONENT);
}
- extract($this->_generateMinMax($bits));
+ extract(self::_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) {
@@ -592,19 +492,19 @@ class RSA
} else {
$num_primes = 2;
}
- extract($this->_generateMinMax($temp + $bits % $temp));
+ extract(self::_generateMinMax($temp + $bits % $temp));
$finalMax = $max;
- extract($this->_generateMinMax($temp));
+ extract(self::_generateMinMax($temp));
$generator = new BigInteger();
- $n = $this->one->copy();
+ $n = self::$one->copy();
if (!empty($partial)) {
extract(unserialize($partial));
} else {
$exponents = $coefficients = $primes = array();
$lcm = array(
- 'top' => $this->one->copy(),
+ 'top' => self::$one->copy(),
'bottom' => false
);
}
@@ -633,8 +533,8 @@ class RSA
if ($i == $num_primes) {
list($min, $temp) = $absoluteMin->divide($n);
- if (!$temp->equals($this->zero)) {
- $min = $min->add($this->one); // ie. ceil()
+ if (!$temp->equals(self::$zero)) {
+ $min = $min->add(self::$one); // ie. ceil()
}
$primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
} else {
@@ -655,8 +555,8 @@ class RSA
}
return array(
- 'privatekey' => '',
- 'publickey' => '',
+ 'privatekey' => false,
+ 'publickey' => false,
'partialkey' => $partialkey
);
}
@@ -669,7 +569,7 @@ class RSA
$n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract($this->one);
+ $temp = $primes[$i]->subtract(self::$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
@@ -682,7 +582,7 @@ class RSA
list($temp) = $lcm['top']->divide($lcm['bottom']);
$gcd = $temp->gcd($e);
$i0 = 1;
- } while (!$gcd->equals($this->one));
+ } while (!$gcd->equals(self::$one));
$d = $e->modInverse($temp);
@@ -701,806 +601,48 @@ class RSA
// coefficient INTEGER, -- (inverse of q) mod p
// otherPrimeInfos OtherPrimeInfos OPTIONAL
// }
+ $privatekey = new RSA();
+ $privatekey->modulus = $n;
+ $privatekey->k = $bits >> 3;
+ $privatekey->publicExponent = $e;
+ $privatekey->exponent = $d;
+ $privatekey->privateExponent = $e;
+ $privatekey->primes = $primes;
+ $privatekey->exponents = $exponents;
+ $privatekey->coefficients = $coefficients;
+
+ $publickey = new RSA();
+ $publickey->modulus = $n;
+ $publickey->k = $bits >> 3;
+ $publickey->exponent = $e;
return array(
- 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
- 'publickey' => $this->_convertPublicKey($n, $e),
+ 'privatekey' => $privatekey,
+ 'publickey' => $publickey,
'partialkey' => false
);
}
/**
- * Convert a private key to the appropriate format.
+ * Pre-loads all the key format plugins
*
+ * @see load()
* @access private
- * @see setPrivateKeyFormat()
- * @param string $RSAPrivateKey
- * @return string
*/
- function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
+ function _loadFileFormats()
{
- $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;
+ if (self::$fileFormats === false) {
+ self::$fileFormats = array();
+ foreach (glob(__DIR__ . '/RSA/*.php') as $file) {
+ $type = 'phpseclib\Crypt\RSA\\' . pathinfo($file, PATHINFO_FILENAME);
+ $meta = new \ReflectionClass($type);
+ if (!$meta->isAbstract()) {
+ self::$fileFormats[] = $type;
}
- return "' . base64_encode($raw['prime1']) . "
\r\n" . - '' . base64_encode($raw['prime2']) . "\r\n" . - '
' . base64_encode($primes[1]->toBytes()) . "
\r\n" . + '' . base64_encode($primes[2]->toBytes()) . "\r\n" . + '