* createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $ciphertext = $publickey->encrypt($plaintext);
+ * $rsa->loadKey($privatekey);
+ * $ciphertext = $rsa->encrypt($plaintext);
*
- * echo $privatekey->decrypt($ciphertext);
+ * $rsa->loadKey($publickey);
+ * echo $rsa->decrypt($ciphertext);
* ?>
*
*
* Here's an example of how to create signatures and verify signatures with this library:
*
* createKey());
*
- * $plaintext = 'terrafrost';
+ * $plaintext = 'terrafrost';
*
- * $signature = $privatekey->sign($plaintext);
+ * $rsa->loadKey($privatekey);
+ * $signature = $rsa->sign($plaintext);
*
- * echo $publickey->verify($plaintext, $signature) ? 'verified' : 'unverified';
+ * $rsa->loadKey($publickey);
+ * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
* ?>
*
*
@@ -45,7 +51,13 @@
namespace phpseclib\Crypt;
-use phpseclib\File\ASN1;
+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;
/**
@@ -59,136 +71,215 @@ class RSA
{
/**#@+
* @access public
- * @see self::encrypt()
- * @see self::decrypt()
+ * @see \phpseclib\Crypt\RSA::encrypt()
+ * @see \phpseclib\Crypt\RSA::decrypt()
*/
/**
* Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
* (OAEP) for encryption / decryption.
*
- * Uses sha256 by default
+ * Uses sha1 by default.
*
- * @see self::setHash()
- * @see self::setMGFHash()
+ * @see \phpseclib\Crypt\RSA::setHash()
+ * @see \phpseclib\Crypt\RSA::setMGFHash()
*/
- const PADDING_OAEP = 1;
+ const ENCRYPTION_OAEP = 1;
/**
* Use PKCS#1 padding.
*
- * Although self::PADDING_OAEP / self::PADDING_PSS offers more security, including PKCS#1 padding is necessary for purposes of backwards
+ * 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 PADDING_PKCS1 = 2;
+ */
+ 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 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;
+ const ENCRYPTION_NONE = 3;
/**#@-*/
/**#@+
* @access public
- * @see self::sign()
- * @see self::verify()
- * @see self::setHash()
- */
+ * @see \phpseclib\Crypt\RSA::sign()
+ * @see \phpseclib\Crypt\RSA::verify()
+ * @see \phpseclib\Crypt\RSA::setHash()
+ */
/**
* Use the Probabilistic Signature Scheme for signing
*
- * Uses sha256 and 0 as the salt length
+ * Uses sha1 by default.
*
- * @see self::setSaltLength()
- * @see self::setMGFHash()
- * @see self::setHash()
- */
- const PADDING_PSS = 4;
+ * @see \phpseclib\Crypt\RSA::setSaltLength()
+ * @see \phpseclib\Crypt\RSA::setMGFHash()
+ */
+ const SIGNATURE_PSS = 1;
/**
- * Use a relaxed version of PKCS#1 padding for signature verification
- */
- const PADDING_RELAXED_PKCS1 = 5;
+ * 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 self::createKey()
- */
+ * @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 self::__construct()
- */
+ * @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 = 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
*/
- static $zero;
+ var $zero;
/**
* Precomputed One
*
- * @var array
+ * @var Array
* @access private
*/
- static $one;
+ var $one;
/**
* Private Key Format
*
- * @var string
+ * @var Integer
* @access private
*/
- var $privateKeyFormat = 'PKCS1';
+ var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
/**
* Public Key Format
*
- * @var string
- * @access private
+ * @var Integer
+ * @access public
*/
- var $publicKeyFormat = 'PKCS8';
+ var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
/**
* Modulus (ie. n)
@@ -217,7 +308,7 @@ class RSA
/**
* Primes for Chinese Remainder Theorem (ie. p and q)
*
- * @var array
+ * @var Array
* @access private
*/
var $primes;
@@ -225,7 +316,7 @@ class RSA
/**
* Exponents for Chinese Remainder Theorem (ie. dP and dQ)
*
- * @var array
+ * @var Array
* @access private
*/
var $exponents;
@@ -233,7 +324,7 @@ class RSA
/**
* Coefficients for Chinese Remainder Theorem (ie. qInv)
*
- * @var array
+ * @var Array
* @access private
*/
var $coefficients;
@@ -241,7 +332,7 @@ class RSA
/**
* Hash name
*
- * @var string
+ * @var String
* @access private
*/
var $hashName;
@@ -257,7 +348,7 @@ class RSA
/**
* Length of hash function output
*
- * @var int
+ * @var Integer
* @access private
*/
var $hLen;
@@ -265,7 +356,7 @@ class RSA
/**
* Length of salt
*
- * @var int
+ * @var Integer
* @access private
*/
var $sLen;
@@ -281,15 +372,31 @@ class RSA
/**
* Length of MGF hash function output
*
- * @var int
+ * @var Integer
* @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;
@@ -297,75 +404,52 @@ class RSA
/**
* Password
*
- * @var string
+ * @var String
* @access private
*/
var $password = false;
/**
- * Loaded File Format
+ * Components
*
- * @var string
+ * 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 $format = false;
+ 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 self::createKey()
- * @var mixed
- * @access public
+ * @see \phpseclib\Crypt\RSA::createKey()
+ * @var Mixed
+ * @Access public
*/
- static $configFile;
+ var $configFile;
/**
- * Supported file formats (lower case)
+ * Public key comment field.
*
- * @see self::_initialize_static_variables()
- * @var array
+ * @var String
* @access private
*/
- 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;
- }
- }
- }
- }
- }
+ var $comment = 'phpseclib-generated-key';
/**
* The constructor
@@ -379,32 +463,7 @@ class RSA
*/
function __construct()
{
- 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();
+ $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
if (!defined('CRYPT_RSA_MODE')) {
switch (true) {
@@ -414,7 +473,11 @@ class RSA
case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
break;
- case extension_loaded('openssl') && file_exists(self::$configFile):
+ // 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):
// some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
ob_start();
@phpinfo();
@@ -454,6 +517,32 @@ 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');
@@ -471,17 +560,16 @@ 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(self::$configFile)) {
- $config['config'] = self::$configFile;
+ if (isset($this->configFile)) {
+ $config['config'] = $this->configFile;
}
$rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
- openssl_pkey_export($rsa, $privatekeystr, null, $config);
- $privatekey = new RSA();
- $privatekey->load($privatekeystr);
+ openssl_pkey_export($rsa, $privatekey, null, $config);
+ $publickey = openssl_pkey_get_details($rsa);
+ $publickey = $publickey['key'];
- $publickeyarr = openssl_pkey_get_details($rsa);
- $publickey = new RSA();
- $publickey->load($publickeyarr['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) {
@@ -499,7 +587,7 @@ class RSA
$e = new BigInteger(CRYPT_RSA_EXPONENT);
}
- extract(self::_generateMinMax($bits));
+ 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) {
@@ -508,17 +596,19 @@ class RSA
} else {
$num_primes = 2;
}
- extract(self::_generateMinMax($temp + $bits % $temp));
+ extract($this->_generateMinMax($temp + $bits % $temp));
$finalMax = $max;
- extract(self::_generateMinMax($temp));
+ extract($this->_generateMinMax($temp));
- $n = clone self::$one;
+ $generator = new BigInteger();
+
+ $n = $this->one->copy();
if (!empty($partial)) {
extract(unserialize($partial));
} else {
$exponents = $coefficients = $primes = array();
$lcm = array(
- 'top' => clone self::$one,
+ 'top' => $this->one->copy(),
'bottom' => false
);
}
@@ -547,12 +637,12 @@ class RSA
if ($i == $num_primes) {
list($min, $temp) = $absoluteMin->divide($n);
- if (!$temp->equals(self::$zero)) {
- $min = $min->add(self::$one); // ie. ceil()
+ if (!$temp->equals($this->zero)) {
+ $min = $min->add($this->one); // ie. ceil()
}
- $primes[$i] = BigInteger::randomPrime($min, $finalMax, $timeout);
+ $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
} else {
- $primes[$i] = BigInteger::randomPrime($min, $max, $timeout);
+ $primes[$i] = $generator->randomPrime($min, $max, $timeout);
}
if ($primes[$i] === false) { // if we've reached the timeout
@@ -569,8 +659,8 @@ class RSA
}
return array(
- 'privatekey' => false,
- 'publickey' => false,
+ 'privatekey' => '',
+ 'publickey' => '',
'partialkey' => $partialkey
);
}
@@ -583,7 +673,7 @@ class RSA
$n = $n->multiply($primes[$i]);
- $temp = $primes[$i]->subtract(self::$one);
+ $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
@@ -596,7 +686,7 @@ class RSA
list($temp) = $lcm['top']->divide($lcm['bottom']);
$gcd = $temp->gcd($e);
$i0 = 1;
- } while (!$gcd->equals(self::$one));
+ } while (!$gcd->equals($this->one));
$d = $e->modInverse($temp);
@@ -615,62 +705,804 @@ 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' => $privatekey,
- 'publickey' => $publickey,
+ 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
+ 'publickey' => $this->_convertPublicKey($n, $e),
'partialkey' => false
);
}
/**
- * Add a fileformat plugin
+ * Convert a private key to the appropriate format.
*
- * 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
+ * @access private
+ * @see setPrivateKeyFormat()
+ * @param String $RSAPrivateKey
+ * @return String
*/
- static function addFileFormat($fullname)
+ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
{
- self::_initialize_static_variables();
+ $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 (class_exists($fullname)) {
- $meta = new \ReflectionClass($path);
- $shortname = $meta->getShortName();
- self::$fileFormats[strtolower($shortname)] = $fullname;
- self::$origFileFormats[] = $shortname;
+ // 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" . - '