* 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);
+ * $signature = $privatekey->sign($plaintext);
*
- * $rsa->loadKey($publickey);
- * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
+ * echo $publickey->verify($plaintext, $signature) ? 'verified' : 'unverified';
* ?>
*
*
@@ -51,13 +45,7 @@
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\File\ASN1;
use phpseclib\Math\BigInteger;
/**
@@ -71,215 +59,136 @@ class RSA
{
/**#@+
* @access public
- * @see \phpseclib\Crypt\RSA::encrypt()
- * @see \phpseclib\Crypt\RSA::decrypt()
+ * @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.
+ * Uses sha256 by default
*
- * @see \phpseclib\Crypt\RSA::setHash()
- * @see \phpseclib\Crypt\RSA::setMGFHash()
+ * @see self::setHash()
+ * @see self::setMGFHash()
*/
- const ENCRYPTION_OAEP = 1;
+ const PADDING_OAEP = 1;
/**
* Use PKCS#1 padding.
*
- * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
+ * Although self::PADDING_OAEP / self::PADDING_PSS 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;
+ */
+ const PADDING_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;
+ const PADDING_NONE = 3;
+ /**
+ * Use PKCS#1 padding with PKCS1 v1.5 compatability
+ *
+ * A PKCS1 v2.1 encrypted message may not successfully decrypt with a PKCS1 v1.5 implementation (such as OpenSSL).
+ */
+ const PADDING_PKCS15_COMPAT = 6;
/**#@-*/
/**#@+
* @access public
- * @see \phpseclib\Crypt\RSA::sign()
- * @see \phpseclib\Crypt\RSA::verify()
- * @see \phpseclib\Crypt\RSA::setHash()
- */
+ * @see self::sign()
+ * @see self::verify()
+ * @see self::setHash()
+ */
/**
* Use the Probabilistic Signature Scheme for signing
*
- * Uses sha1 by default.
+ * Uses sha256 and 0 as the salt length
*
- * @see \phpseclib\Crypt\RSA::setSaltLength()
- * @see \phpseclib\Crypt\RSA::setMGFHash()
- */
- const SIGNATURE_PSS = 1;
+ * @see self::setSaltLength()
+ * @see self::setMGFHash()
+ * @see self::setHash()
+ */
+ const PADDING_PSS = 4;
/**
- * 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;
+ * Use a relaxed version of PKCS#1 padding for signature verification
+ */
+ const PADDING_RELAXED_PKCS1 = 5;
/**#@-*/
/**#@+
* @access private
- * @see \phpseclib\Crypt\RSA::createKey()
- */
+ * @see self::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()
- */
+ * @see self::__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 = 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
+ * @var array
* @access private
*/
- var $zero;
+ static $zero;
/**
* Precomputed One
*
- * @var Array
+ * @var array
* @access private
*/
- var $one;
+ static $one;
/**
* Private Key Format
*
- * @var Integer
+ * @var string
* @access private
*/
- var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
+ var $privateKeyFormat = 'PKCS1';
/**
* Public Key Format
*
- * @var Integer
- * @access public
+ * @var string
+ * @access private
*/
- var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
+ var $publicKeyFormat = 'PKCS8';
/**
* Modulus (ie. n)
@@ -308,7 +217,7 @@ class RSA
/**
* Primes for Chinese Remainder Theorem (ie. p and q)
*
- * @var Array
+ * @var array
* @access private
*/
var $primes;
@@ -316,7 +225,7 @@ class RSA
/**
* Exponents for Chinese Remainder Theorem (ie. dP and dQ)
*
- * @var Array
+ * @var array
* @access private
*/
var $exponents;
@@ -324,7 +233,7 @@ class RSA
/**
* Coefficients for Chinese Remainder Theorem (ie. qInv)
*
- * @var Array
+ * @var array
* @access private
*/
var $coefficients;
@@ -332,7 +241,7 @@ class RSA
/**
* Hash name
*
- * @var String
+ * @var string
* @access private
*/
var $hashName;
@@ -348,7 +257,7 @@ class RSA
/**
* Length of hash function output
*
- * @var Integer
+ * @var int
* @access private
*/
var $hLen;
@@ -356,7 +265,7 @@ class RSA
/**
* Length of salt
*
- * @var Integer
+ * @var int
* @access private
*/
var $sLen;
@@ -372,31 +281,15 @@ class RSA
/**
* Length of MGF hash function output
*
- * @var Integer
+ * @var int
* @access private
*/
var $mgfHLen;
- /**
- * Encryption mode
- *
- * @var Integer
- * @access private
- */
- var $encryptionMode = self::ENCRYPTION_OAEP;
-
- /**
- * Signature mode
- *
- * @var Integer
- * @access private
- */
- var $signatureMode = self::SIGNATURE_PSS;
-
/**
* Public Exponent
*
- * @var Mixed
+ * @var mixed
* @access private
*/
var $publicExponent = false;
@@ -404,52 +297,75 @@ class RSA
/**
* Password
*
- * @var String
+ * @var string
* @access private
*/
var $password = false;
/**
- * Components
+ * Loaded File Format
*
- * 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
+ * @var string
* @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;
+ var $format = false;
/**
* OpenSSL configuration file name.
*
* Set to null to use system configuration file.
- * @see \phpseclib\Crypt\RSA::createKey()
- * @var Mixed
- * @Access public
+ *
+ * @see self::createKey()
+ * @var mixed
+ * @access public
*/
- var $configFile;
+ static $configFile;
/**
- * Public key comment field.
+ * Supported file formats (lower case)
*
- * @var String
+ * @see self::_initialize_static_variables()
+ * @var array
* @access private
*/
- var $comment = 'phpseclib-generated-key';
+ static $fileFormats = false;
+
+ /**
+ * Supported file formats (original case)
+ *
+ * @see self::_initialize_static_variables()
+ * @var array
+ * @access private
+ */
+ static $origFileFormats = 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';
+
+ if (self::$fileFormats === false) {
+ self::$fileFormats = array();
+ foreach (glob(__DIR__ . '/RSA/*.php') as $file) {
+ $name = pathinfo($file, PATHINFO_FILENAME);
+ $type = 'phpseclib\Crypt\RSA\\' . $name;
+ $meta = new \ReflectionClass($type);
+ if (!$meta->isAbstract()) {
+ self::$fileFormats[strtolower($name)] = $type;
+ self::$origFileFormats[] = $name;
+ }
+ }
+ }
+ }
+ }
/**
* The constructor
@@ -463,7 +379,32 @@ class RSA
*/
function __construct()
{
- $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
+ self::_initialize_static_variables();
+
+ $this->hash = new Hash('sha256');
+ $this->hLen = $this->hash->getLength();
+ $this->hashName = 'sha256';
+ $this->mgfHash = new Hash('sha256');
+ $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 = 2048, $timeout = false, $partial = array())
+ {
+ self::_initialize_static_variables();
if (!defined('CRYPT_RSA_MODE')) {
switch (true) {
@@ -473,11 +414,7 @@ class RSA
case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
break;
- // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0
- case !function_exists('openssl_pkey_get_details'):
- define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
- break;
- case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && 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();
@@ -517,32 +454,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 optional Integer $bits
- * @param optional Integer $timeout
- * @param optional 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');
@@ -560,16 +471,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) {
@@ -587,7 +499,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) {
@@ -596,19 +508,17 @@ 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 = clone self::$one;
if (!empty($partial)) {
extract(unserialize($partial));
} else {
$exponents = $coefficients = $primes = array();
$lcm = array(
- 'top' => $this->one->copy(),
+ 'top' => clone self::$one,
'bottom' => false
);
}
@@ -637,12 +547,12 @@ 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);
+ $primes[$i] = BigInteger::randomPrime($min, $finalMax, $timeout);
} else {
- $primes[$i] = $generator->randomPrime($min, $max, $timeout);
+ $primes[$i] = BigInteger::randomPrime($min, $max, $timeout);
}
if ($primes[$i] === false) { // if we've reached the timeout
@@ -659,8 +569,8 @@ class RSA
}
return array(
- 'privatekey' => '',
- 'publickey' => '',
+ 'privatekey' => false,
+ 'publickey' => false,
'partialkey' => $partialkey
);
}
@@ -673,7 +583,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
@@ -686,7 +596,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);
@@ -705,804 +615,62 @@ 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.
+ * Add a fileformat plugin
*
- * @access private
- * @see setPrivateKeyFormat()
- * @param String $RSAPrivateKey
- * @return String
+ * The plugin needs to either already be loaded or be auto-loadable.
+ * Loading a plugin whose shortname overwrite an existing shortname will overwrite the old plugin.
+ *
+ * @see self::load()
+ * @param string $fullname
+ * @access public
+ * @return bool
*/
- function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
+ static function addFileFormat($fullname)
{
- $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)
- );
+ self::_initialize_static_variables();
- // 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 "' . 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" . + '