--- /dev/null
+<?php\r
+/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */\r
+\r
+/**\r
+ * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.\r
+ *\r
+ * PHP versions 4 and 5\r
+ *\r
+ * Here's an example of how to encrypt and decrypt text with this library:\r
+ * <code>\r
+ * <?php\r
+ * include('Crypt/RSA.php');\r
+ *\r
+ * $rsa = new Crypt_RSA();\r
+ * extract($rsa->createKey());\r
+ *\r
+ * $plaintext = 'terrafrost';\r
+ *\r
+ * $rsa->loadKey($privatekey);\r
+ * $ciphertext = $rsa->encrypt($plaintext);\r
+ *\r
+ * $rsa->loadKey($publickey);\r
+ * echo $rsa->decrypt($ciphertext);\r
+ * ?>\r
+ * </code>\r
+ *\r
+ * Here's an example of how to create signatures and verify signatures with this library:\r
+ * <code>\r
+ * <?php\r
+ * include('Crypt/RSA.php');\r
+ *\r
+ * $rsa = new Crypt_RSA();\r
+ * extract($rsa->createKey());\r
+ *\r
+ * $plaintext = 'terrafrost';\r
+ *\r
+ * $rsa->loadKey($privatekey);\r
+ * $signature = $rsa->sign($plaintext);\r
+ *\r
+ * $rsa->loadKey($publickey);\r
+ * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';\r
+ * ?>\r
+ * </code>\r
+ *\r
+ * LICENSE: This library is free software; you can redistribute it and/or\r
+ * modify it under the terms of the GNU Lesser General Public\r
+ * License as published by the Free Software Foundation; either\r
+ * version 2.1 of the License, or (at your option) any later version.\r
+ *\r
+ * This library is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r
+ * Lesser General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU Lesser General Public\r
+ * License along with this library; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\r
+ * MA 02111-1307 USA\r
+ *\r
+ * @category Crypt\r
+ * @package Crypt_RSA\r
+ * @author Jim Wigginton <terrafrost@php.net>\r
+ * @copyright MMIX Jim Wigginton\r
+ * @license http://www.gnu.org/licenses/lgpl.txt\r
+ * @version $Id: RSA.php,v 1.15 2010/04/10 15:57:02 terrafrost Exp $\r
+ * @link http://phpseclib.sourceforge.net\r
+ */\r
+\r
+/**\r
+ * Include Math_BigInteger\r
+ */\r
+require_once('Math/BigInteger.php');\r
+\r
+/**\r
+ * Include Crypt_Random\r
+ */\r
+require_once('Crypt/Random.php');\r
+\r
+/**\r
+ * Include Crypt_Hash\r
+ */\r
+require_once('Crypt/Hash.php');\r
+\r
+/**#@+\r
+ * @access public\r
+ * @see Crypt_RSA::encrypt()\r
+ * @see Crypt_RSA::decrypt()\r
+ */\r
+/**\r
+ * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}\r
+ * (OAEP) for encryption / decryption.\r
+ *\r
+ * Uses sha1 by default.\r
+ *\r
+ * @see Crypt_RSA::setHash()\r
+ * @see Crypt_RSA::setMGFHash()\r
+ */\r
+define('CRYPT_RSA_ENCRYPTION_OAEP', 1);\r
+/**\r
+ * Use PKCS#1 padding.\r
+ *\r
+ * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards\r
+ * compatability with protocols (like SSH-1) written before OAEP's introduction.\r
+ */\r
+define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);\r
+/**#@-*/\r
+\r
+/**#@+\r
+ * @access public\r
+ * @see Crypt_RSA::sign()\r
+ * @see Crypt_RSA::verify()\r
+ * @see Crypt_RSA::setHash()\r
+ */\r
+/**\r
+ * Use the Probabilistic Signature Scheme for signing\r
+ *\r
+ * Uses sha1 by default.\r
+ *\r
+ * @see Crypt_RSA::setSaltLength()\r
+ * @see Crypt_RSA::setMGFHash()\r
+ */\r
+define('CRYPT_RSA_SIGNATURE_PSS', 1);\r
+/**\r
+ * Use the PKCS#1 scheme by default.\r
+ *\r
+ * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards\r
+ * compatability with protocols (like SSH-2) written before PSS's introduction.\r
+ */\r
+define('CRYPT_RSA_SIGNATURE_PKCS1', 2);\r
+/**#@-*/\r
+\r
+/**#@+\r
+ * @access private\r
+ * @see Crypt_RSA::createKey()\r
+ */\r
+/**\r
+ * ASN1 Integer\r
+ */\r
+define('CRYPT_RSA_ASN1_INTEGER', 2);\r
+/**\r
+ * ASN1 Sequence (with the constucted bit set)\r
+ */\r
+define('CRYPT_RSA_ASN1_SEQUENCE', 48);\r
+/**#@-*/\r
+\r
+/**#@+\r
+ * @access private\r
+ * @see Crypt_RSA::Crypt_RSA()\r
+ */\r
+/**\r
+ * To use the pure-PHP implementation\r
+ */\r
+define('CRYPT_RSA_MODE_INTERNAL', 1);\r
+/**\r
+ * To use the OpenSSL library\r
+ *\r
+ * (if enabled; otherwise, the internal implementation will be used)\r
+ */\r
+define('CRYPT_RSA_MODE_OPENSSL', 2);\r
+/**#@-*/\r
+\r
+/**#@+\r
+ * @access public\r
+ * @see Crypt_RSA::createKey()\r
+ * @see Crypt_RSA::setPrivateKeyFormat()\r
+ */\r
+/**\r
+ * PKCS#1 formatted private key\r
+ *\r
+ * Used by OpenSSH\r
+ */\r
+define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);\r
+/**#@-*/\r
+\r
+/**#@+\r
+ * @access public\r
+ * @see Crypt_RSA::createKey()\r
+ * @see Crypt_RSA::setPublicKeyFormat()\r
+ */\r
+/**\r
+ * Raw public key\r
+ *\r
+ * An array containing two Math_BigInteger objects.\r
+ *\r
+ * The exponent can be indexed with any of the following:\r
+ *\r
+ * 0, e, exponent, publicExponent\r
+ *\r
+ * The modulus can be indexed with any of the following:\r
+ *\r
+ * 1, n, modulo, modulus\r
+ */\r
+define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 1);\r
+/**\r
+ * PKCS#1 formatted public key\r
+ */\r
+define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 2);\r
+/**\r
+ * OpenSSH formatted public key\r
+ *\r
+ * Place in $HOME/.ssh/authorized_keys\r
+ */\r
+define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 3);\r
+/**#@-*/\r
+\r
+/**\r
+ * Pure-PHP PKCS#1 compliant implementation of RSA.\r
+ *\r
+ * @author Jim Wigginton <terrafrost@php.net>\r
+ * @version 0.1.0\r
+ * @access public\r
+ * @package Crypt_RSA\r
+ */\r
+class Crypt_RSA {\r
+ /**\r
+ * Precomputed Zero\r
+ *\r
+ * @var Array\r
+ * @access private\r
+ */\r
+ var $zero;\r
+\r
+ /**\r
+ * Precomputed One\r
+ *\r
+ * @var Array\r
+ * @access private\r
+ */\r
+ var $one;\r
+\r
+ /**\r
+ * Private Key Format\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;\r
+\r
+ /**\r
+ * Public Key Format\r
+ *\r
+ * @var Integer\r
+ * @access public\r
+ */\r
+ var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;\r
+\r
+ /**\r
+ * Modulus (ie. n)\r
+ *\r
+ * @var Math_BigInteger\r
+ * @access private\r
+ */\r
+ var $modulus;\r
+\r
+ /**\r
+ * Modulus length\r
+ *\r
+ * @var Math_BigInteger\r
+ * @access private\r
+ */\r
+ var $k;\r
+\r
+ /**\r
+ * Exponent (ie. e or d)\r
+ *\r
+ * @var Math_BigInteger\r
+ * @access private\r
+ */\r
+ var $exponent;\r
+\r
+ /**\r
+ * Primes for Chinese Remainder Theorem (ie. p and q)\r
+ *\r
+ * @var Array\r
+ * @access private\r
+ */\r
+ var $primes;\r
+\r
+ /**\r
+ * Exponents for Chinese Remainder Theorem (ie. dP and dQ)\r
+ *\r
+ * @var Array\r
+ * @access private\r
+ */\r
+ var $exponents;\r
+\r
+ /**\r
+ * Coefficients for Chinese Remainder Theorem (ie. qInv)\r
+ *\r
+ * @var Array\r
+ * @access private\r
+ */\r
+ var $coefficients;\r
+\r
+ /**\r
+ * Hash name\r
+ *\r
+ * @var String\r
+ * @access private\r
+ */\r
+ var $hashName;\r
+\r
+ /**\r
+ * Hash function\r
+ *\r
+ * @var Crypt_Hash\r
+ * @access private\r
+ */\r
+ var $hash;\r
+\r
+ /**\r
+ * Length of hash function output\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $hLen;\r
+\r
+ /**\r
+ * Length of salt\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $sLen;\r
+\r
+ /**\r
+ * Hash function for the Mask Generation Function\r
+ *\r
+ * @var Crypt_Hash\r
+ * @access private\r
+ */\r
+ var $mgfHash;\r
+\r
+ /**\r
+ * Length of MGF hash function output\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $mgfHLen;\r
+\r
+ /**\r
+ * Encryption mode\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;\r
+\r
+ /**\r
+ * Signature mode\r
+ *\r
+ * @var Integer\r
+ * @access private\r
+ */\r
+ var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;\r
+\r
+ /**\r
+ * Public Exponent\r
+ *\r
+ * @var Mixed\r
+ * @access private\r
+ */\r
+ var $publicExponent = false;\r
+\r
+ /**\r
+ * Password\r
+ *\r
+ * @var String\r
+ * @access private\r
+ */\r
+ var $password = '';\r
+\r
+ /**\r
+ * The constructor\r
+ *\r
+ * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason\r
+ * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires\r
+ * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.\r
+ *\r
+ * @return Crypt_RSA\r
+ * @access public\r
+ */\r
+ function Crypt_RSA()\r
+ {\r
+ if ( !defined('CRYPT_RSA_MODE') ) {\r
+ switch (true) {\r
+ //case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):\r
+ // define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);\r
+ // break;\r
+ default:\r
+ define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);\r
+ }\r
+ }\r
+\r
+ $this->zero = new Math_BigInteger();\r
+ $this->one = new Math_BigInteger(1);\r
+\r
+ $this->hash = new Crypt_Hash('sha1');\r
+ $this->hLen = $this->hash->getLength();\r
+ $this->hashName = 'sha1';\r
+ $this->mgfHash = new Crypt_Hash('sha1');\r
+ $this->mgfHLen = $this->mgfHash->getLength();\r
+ }\r
+\r
+ /**\r
+ * Create public / private key pair\r
+ *\r
+ * Returns an array with the following three elements:\r
+ * - 'privatekey': The private key.\r
+ * - 'publickey': The public key.\r
+ * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).\r
+ * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.\r
+ *\r
+ * @access public\r
+ * @param optional Integer $bits\r
+ * @param optional Integer $timeout\r
+ * @param optional Math_BigInteger $p\r
+ */\r
+ function createKey($bits = 1024, $timeout = false, $partial = array())\r
+ {\r
+ if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL ) {\r
+ $rsa = openssl_pkey_new(array('private_key_bits' => $bits));\r
+ openssl_pkey_export($rsa, $privatekey);\r
+ $publickey = openssl_pkey_get_details($rsa);\r
+ $publickey = $publickey['key'];\r
+\r
+ if ($this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_PKCS1) {\r
+ $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));\r
+ $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));\r
+ }\r
+\r
+ return array(\r
+ 'privatekey' => $privatekey,\r
+ 'publickey' => $publickey,\r
+ 'partialkey' => false\r
+ );\r
+ }\r
+\r
+ static $e;\r
+ if (!isset($e)) {\r
+ if (!defined('CRYPT_RSA_EXPONENT')) {\r
+ // http://en.wikipedia.org/wiki/65537_%28number%29\r
+ define('CRYPT_RSA_EXPONENT', '65537');\r
+ }\r
+ if (!defined('CRYPT_RSA_COMMENT')) {\r
+ define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');\r
+ }\r
+ // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller\r
+ // than 256 bits.\r
+ if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {\r
+ define('CRYPT_RSA_SMALLEST_PRIME', 4096);\r
+ }\r
+\r
+ $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);\r
+ }\r
+\r
+ extract($this->_generateMinMax($bits));\r
+ $absoluteMin = $min;\r
+ $temp = $bits >> 1;\r
+ if ($temp > CRYPT_RSA_SMALLEST_PRIME) {\r
+ $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);\r
+ $temp = CRYPT_RSA_SMALLEST_PRIME;\r
+ } else {\r
+ $num_primes = 2;\r
+ }\r
+ extract($this->_generateMinMax($temp + $bits % $temp));\r
+ $finalMax = $max;\r
+ extract($this->_generateMinMax($temp));\r
+\r
+ $generator = new Math_BigInteger();\r
+ $generator->setRandomGenerator('crypt_random');\r
+\r
+ $n = $this->one->copy();\r
+ if (!empty($partial)) {\r
+ extract(unserialize($partial));\r
+ } else {\r
+ $exponents = $coefficients = $primes = array();\r
+ $lcm = array(\r
+ 'top' => $this->one->copy(),\r
+ 'bottom' => false\r
+ );\r
+ }\r
+\r
+ $start = time();\r
+ $i0 = count($primes) + 1;\r
+\r
+ do {\r
+ for ($i = $i0; $i <= $num_primes; $i++) {\r
+ if ($timeout !== false) {\r
+ $timeout-= time() - $start;\r
+ $start = time();\r
+ if ($timeout <= 0) {\r
+ return serialize(array(\r
+ 'privatekey' => '',\r
+ 'publickey' => '',\r
+ 'partialkey' => array(\r
+ 'primes' => $primes,\r
+ 'coefficients' => $coefficients,\r
+ 'lcm' => $lcm,\r
+ 'exponents' => $exponents\r
+ )\r
+ ));\r
+ }\r
+ }\r
+\r
+ if ($i == $num_primes) {\r
+ list($min, $temp) = $absoluteMin->divide($n);\r
+ if (!$temp->equals($this->zero)) {\r
+ $min = $min->add($this->one); // ie. ceil()\r
+ }\r
+ $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);\r
+ } else {\r
+ $primes[$i] = $generator->randomPrime($min, $max, $timeout);\r
+ }\r
+\r
+ if ($primes[$i] === false) { // if we've reached the timeout\r
+ return array(\r
+ 'privatekey' => '',\r
+ 'publickey' => '',\r
+ 'partialkey' => empty($primes) ? '' : serialize(array(\r
+ 'primes' => array_slice($primes, 0, $i - 1),\r
+ 'coefficients' => $coefficients,\r
+ 'lcm' => $lcm,\r
+ 'exponents' => $exponents\r
+ ))\r
+ );\r
+ }\r
+\r
+ // the first coefficient is calculated differently from the rest\r
+ // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])\r
+ if ($i > 2) {\r
+ $coefficients[$i] = $n->modInverse($primes[$i]);\r
+ }\r
+\r
+ $n = $n->multiply($primes[$i]);\r
+\r
+ $temp = $primes[$i]->subtract($this->one);\r
+\r
+ // textbook RSA implementations use Euler's totient function instead of the least common multiple.\r
+ // see http://en.wikipedia.org/wiki/Euler%27s_totient_function\r
+ $lcm['top'] = $lcm['top']->multiply($temp);\r
+ $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);\r
+\r
+ $exponents[$i] = $e->modInverse($temp);\r
+ }\r
+\r
+ list($lcm) = $lcm['top']->divide($lcm['bottom']);\r
+ $gcd = $lcm->gcd($e);\r
+ $i0 = 1;\r
+ } while (!$gcd->equals($this->one));\r
+\r
+ $d = $e->modInverse($lcm);\r
+\r
+ $coefficients[2] = $primes[2]->modInverse($primes[1]);\r
+\r
+ // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:\r
+ // RSAPrivateKey ::= SEQUENCE {\r
+ // version Version,\r
+ // modulus INTEGER, -- n\r
+ // publicExponent INTEGER, -- e\r
+ // privateExponent INTEGER, -- d\r
+ // prime1 INTEGER, -- p\r
+ // prime2 INTEGER, -- q\r
+ // exponent1 INTEGER, -- d mod (p-1)\r
+ // exponent2 INTEGER, -- d mod (q-1)\r
+ // coefficient INTEGER, -- (inverse of q) mod p\r
+ // otherPrimeInfos OtherPrimeInfos OPTIONAL\r
+ // }\r
+\r
+ return array(\r
+ 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),\r
+ 'publickey' => $this->_convertPublicKey($n, $e),\r
+ 'partialkey' => false\r
+ );\r
+ }\r
+\r
+ /**\r
+ * Convert a private key to the appropriate format.\r
+ *\r
+ * @access private\r
+ * @see setPrivateKeyFormat()\r
+ * @param String $RSAPrivateKey\r
+ * @return String\r
+ */\r
+ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)\r
+ {\r
+ $num_primes = count($primes);\r
+ $raw = array(\r
+ 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi\r
+ 'modulus' => $n->toBytes(true),\r
+ 'publicExponent' => $e->toBytes(true),\r
+ 'privateExponent' => $d->toBytes(true),\r
+ 'prime1' => $primes[1]->toBytes(true),\r
+ 'prime2' => $primes[2]->toBytes(true),\r
+ 'exponent1' => $exponents[1]->toBytes(true),\r
+ 'exponent2' => $exponents[2]->toBytes(true),\r
+ 'coefficient' => $coefficients[2]->toBytes(true)\r
+ );\r
+\r
+ // if the format in question does not support multi-prime rsa and multi-prime rsa was used,\r
+ // call _convertPublicKey() instead.\r
+ switch ($this->privateKeyFormat) {\r
+ default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1\r
+ $components = array();\r
+ foreach ($raw as $name => $value) {\r
+ $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);\r
+ }\r
+\r
+ $RSAPrivateKey = implode('', $components);\r
+\r
+ if ($num_primes > 2) {\r
+ $OtherPrimeInfos = '';\r
+ for ($i = 3; $i <= $num_primes; $i++) {\r
+ // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo\r
+ //\r
+ // OtherPrimeInfo ::= SEQUENCE {\r
+ // prime INTEGER, -- ri\r
+ // exponent INTEGER, -- di\r
+ // coefficient INTEGER -- ti\r
+ // }\r
+ $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));\r
+ $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));\r
+ $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));\r
+ $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);\r
+ }\r
+ $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);\r
+ }\r
+\r
+ $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);\r
+\r
+ if (!empty($this->password)) {\r
+ $iv = $this->_random(8);\r
+ $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key\r
+ $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);\r
+ if (!class_exists('Crypt_TripleDES')) {\r
+ require_once('Crypt/TripleDES.php');\r
+ }\r
+ $des = new Crypt_TripleDES();\r
+ $des->setKey($symkey);\r
+ $des->setIV($iv);\r
+ $iv = strtoupper(bin2hex($iv));\r
+ $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .\r
+ "Proc-Type: 4,ENCRYPTED\r\n" .\r
+ "DEK-Info: DES-EDE3-CBC,$iv\r\n" .\r
+ "\r\n" .\r
+ chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .\r
+ '-----END RSA PRIVATE KEY-----';\r
+ } else {\r
+ $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .\r
+ chunk_split(base64_encode($RSAPrivateKey)) .\r
+ '-----END RSA PRIVATE KEY-----';\r
+ }\r
+\r
+ return $RSAPrivateKey;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Convert a public key to the appropriate format\r
+ *\r
+ * @access private\r
+ * @see setPublicKeyFormat()\r
+ * @param String $RSAPrivateKey\r
+ * @return String\r
+ */\r
+ function _convertPublicKey($n, $e)\r
+ {\r
+ $modulus = $n->toBytes(true);\r
+ $publicExponent = $e->toBytes(true);\r
+\r
+ switch ($this->publicKeyFormat) {\r
+ case CRYPT_RSA_PUBLIC_FORMAT_RAW:\r
+ return array('e' => $e->copy(), 'n' => $n->copy());\r
+ case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:\r
+ // from <http://tools.ietf.org/html/rfc4253#page-15>:\r
+ // string "ssh-rsa"\r
+ // mpint e\r
+ // mpint n\r
+ $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);\r
+ $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;\r
+\r
+ return $RSAPublicKey;\r
+ default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1\r
+ // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:\r
+ // RSAPublicKey ::= SEQUENCE {\r
+ // modulus INTEGER, -- n\r
+ // publicExponent INTEGER -- e\r
+ // }\r
+ $components = array(\r
+ 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),\r
+ 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)\r
+ );\r
+\r
+ $RSAPublicKey = pack('Ca*a*a*',\r
+ CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),\r
+ $components['modulus'], $components['publicExponent']\r
+ );\r
+\r
+ $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .\r
+ chunk_split(base64_encode($RSAPublicKey)) .\r
+ '-----END PUBLIC KEY-----';\r
+\r
+ return $RSAPublicKey;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Break a public or private key down into its constituant components\r
+ *\r
+ * @access private\r
+ * @see _convertPublicKey()\r
+ * @see _convertPrivateKey()\r
+ * @param String $key\r
+ * @param Integer $type\r
+ * @return Array\r
+ */\r
+ function _parseKey($key, $type)\r
+ {\r
+ switch ($type) {\r
+ case CRYPT_RSA_PUBLIC_FORMAT_RAW:\r
+ if (!is_array($key)) {\r
+ return false;\r
+ }\r
+ $components = array();\r
+ switch (true) {\r
+ case isset($key['e']):\r
+ $components['publicExponent'] = $key['e']->copy();\r
+ break;\r
+ case isset($key['exponent']):\r
+ $components['publicExponent'] = $key['exponent']->copy();\r
+ break;\r
+ case isset($key['publicExponent']):\r
+ $components['publicExponent'] = $key['publicExponent']->copy();\r
+ break;\r
+ case isset($key[0]):\r
+ $components['publicExponent'] = $key[0]->copy();\r
+ }\r
+ switch (true) {\r
+ case isset($key['n']):\r
+ $components['modulus'] = $key['n']->copy();\r
+ break;\r
+ case isset($key['modulo']):\r
+ $components['modulus'] = $key['modulo']->copy();\r
+ break;\r
+ case isset($key['modulus']):\r
+ $components['modulus'] = $key['modulus']->copy();\r
+ break;\r
+ case isset($key[1]):\r
+ $components['modulus'] = $key[1]->copy();\r
+ }\r
+ return $components;\r
+ case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:\r
+ case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:\r
+ /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is\r
+ "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to\r
+ protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding\r
+ two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:\r
+\r
+ http://tools.ietf.org/html/rfc1421#section-4.6.1.1\r
+ http://tools.ietf.org/html/rfc1421#section-4.6.1.3\r
+\r
+ DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.\r
+ DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation\r
+ function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's\r
+ own implementation. ie. the implementation *is* the standard and any bugs that may exist in that \r
+ implementation are part of the standard, as well.\r
+\r
+ * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */\r
+ if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {\r
+ $iv = pack('H*', trim($matches[2]));\r
+ $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key\r
+ $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);\r
+ $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);\r
+ $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;\r
+ if ($ciphertext === false) {\r
+ $ciphertext = $key;\r
+ }\r
+ switch ($matches[1]) {\r
+ case 'DES-EDE3-CBC':\r
+ if (!class_exists('Crypt_TripleDES')) {\r
+ require_once('Crypt/TripleDES.php');\r
+ }\r
+ $crypto = new Crypt_TripleDES();\r
+ break;\r
+ case 'DES-CBC':\r
+ if (!class_exists('Crypt_DES')) {\r
+ require_once('Crypt/DES.php');\r
+ }\r
+ $crypto = new Crypt_DES();\r
+ break;\r
+ default:\r
+ return false;\r
+ }\r
+ $crypto->setKey($symkey);\r
+ $crypto->setIV($iv);\r
+ $decoded = $crypto->decrypt($ciphertext);\r
+ } else {\r
+ $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);\r
+ $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;\r
+ }\r
+\r
+ if ($decoded !== false) {\r
+ $key = $decoded;\r
+ }\r
+\r
+ $components = array();\r
+\r
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {\r
+ return false;\r
+ }\r
+ if ($this->_decodeLength($key) != strlen($key)) {\r
+ return false;\r
+ }\r
+\r
+ $tag = ord($this->_string_shift($key));\r
+ if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {\r
+ /* intended for keys for which OpenSSL's asn1parse returns the following:\r
+\r
+ 0:d=0 hl=4 l= 290 cons: SEQUENCE\r
+ 4:d=1 hl=2 l= 13 cons: SEQUENCE\r
+ 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption\r
+ 17:d=2 hl=2 l= 0 prim: NULL\r
+ 19:d=1 hl=4 l= 271 prim: BIT STRING */\r
+ $this->_string_shift($key, $this->_decodeLength($key));\r
+ $this->_string_shift($key); // skip over the BIT STRING tag\r
+ $this->_decodeLength($key); // skip over the BIT STRING length\r
+ // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of\r
+ // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."\r
+ // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)\r
+ $this->_string_shift($key);\r
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {\r
+ return false;\r
+ }\r
+ if ($this->_decodeLength($key) != strlen($key)) {\r
+ return false;\r
+ }\r
+ $tag = ord($this->_string_shift($key));\r
+ }\r
+ if ($tag != CRYPT_RSA_ASN1_INTEGER) {\r
+ return false;\r
+ }\r
+\r
+ $length = $this->_decodeLength($key);\r
+ $temp = $this->_string_shift($key, $length);\r
+ if (strlen($temp) != 1 || ord($temp) > 2) {\r
+ $components['modulus'] = new Math_BigInteger($temp, -256);\r
+ $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER\r
+ $length = $this->_decodeLength($key);\r
+ $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+\r
+ return $components;\r
+ }\r
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {\r
+ return false;\r
+ }\r
+ $length = $this->_decodeLength($key);\r
+ $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));\r
+\r
+ if (!empty($key)) {\r
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {\r
+ return false;\r
+ }\r
+ $this->_decodeLength($key);\r
+ while (!empty($key)) {\r
+ if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {\r
+ return false;\r
+ }\r
+ $this->_decodeLength($key);\r
+ $key = substr($key, 1);\r
+ $length = $this->_decodeLength($key);\r
+ $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ $this->_string_shift($key);\r
+ $length = $this->_decodeLength($key);\r
+ $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ }\r
+ }\r
+\r
+ return $components;\r
+ case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:\r
+ $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));\r
+ if ($key === false) {\r
+ return false;\r
+ }\r
+\r
+ $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";\r
+\r
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));\r
+ $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));\r
+ $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);\r
+\r
+ if ($cleanup && strlen($key)) {\r
+ extract(unpack('Nlength', $this->_string_shift($key, 4)));\r
+ return array(\r
+ 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),\r
+ 'publicExponent' => $modulus\r
+ );\r
+ } else {\r
+ return array(\r
+ 'modulus' => $modulus,\r
+ 'publicExponent' => $publicExponent\r
+ );\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Loads a public or private key\r
+ *\r
+ * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)\r
+ *\r
+ * @access public\r
+ * @param String $key\r
+ * @param Integer $type optional\r
+ */\r
+ function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)\r
+ {\r
+ $components = $this->_parseKey($key, $type);\r
+ if ($components === false) {\r
+ return false;\r
+ }\r
+\r
+ $this->modulus = $components['modulus'];\r
+ $this->k = strlen($this->modulus->toBytes());\r
+ $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];\r
+ if (isset($components['primes'])) {\r
+ $this->primes = $components['primes'];\r
+ $this->exponents = $components['exponents'];\r
+ $this->coefficients = $components['coefficients'];\r
+ $this->publicExponent = $components['publicExponent'];\r
+ } else {\r
+ $this->primes = array();\r
+ $this->exponents = array();\r
+ $this->coefficients = array();\r
+ $this->publicExponent = false;\r
+ }\r
+\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * Sets the password\r
+ *\r
+ * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.\r
+ * Or rather, pass in $password such that empty($password) is true.\r
+ *\r
+ * @see createKey()\r
+ * @see loadKey()\r
+ * @access public\r
+ * @param String $password\r
+ */\r
+ function setPassword($password)\r
+ {\r
+ $this->password = $password;\r
+ }\r
+\r
+ /**\r
+ * Defines the public key\r
+ *\r
+ * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when\r
+ * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a\r
+ * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys\r
+ * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public\r
+ * exponent this won't work unless you manually add the public exponent.\r
+ *\r
+ * Do note that when a new key is loaded the index will be cleared.\r
+ *\r
+ * Returns true on success, false on failure\r
+ *\r
+ * @see getPublicKey()\r
+ * @access public\r
+ * @param String $key\r
+ * @param Integer $type optional\r
+ * @return Boolean\r
+ */\r
+ function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)\r
+ {\r
+ $components = $this->_parseKey($key, $type);\r
+ if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {\r
+ return false;\r
+ }\r
+ $this->publicExponent = $components['publicExponent'];\r
+ }\r
+\r
+ /**\r
+ * Returns the public key\r
+ *\r
+ * The public key is only returned under two circumstances - if the private key had the public key embedded within it\r
+ * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this\r
+ * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.\r
+ *\r
+ * @see getPublicKey()\r
+ * @access public\r
+ * @param String $key\r
+ * @param Integer $type optional\r
+ */\r
+ function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)\r
+ {\r
+ if (empty($this->modulus) || empty($this->publicExponent)) {\r
+ return false;\r
+ }\r
+\r
+ $oldFormat = $this->publicKeyFormat;\r
+ $this->publicKeyFormat = $type;\r
+ $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);\r
+ $this->publicKeyFormat = $oldFormat;\r
+ return $temp;\r
+ }\r
+\r
+ /**\r
+ * Generates the smallest and largest numbers requiring $bits bits\r
+ *\r
+ * @access private\r
+ * @param Integer $bits\r
+ * @return Array\r
+ */\r
+ function _generateMinMax($bits)\r
+ {\r
+ $bytes = $bits >> 3;\r
+ $min = str_repeat(chr(0), $bytes);\r
+ $max = str_repeat(chr(0xFF), $bytes);\r
+ $msb = $bits & 7;\r
+ if ($msb) {\r
+ $min = chr(1 << ($msb - 1)) . $min;\r
+ $max = chr((1 << $msb) - 1) . $max;\r
+ } else {\r
+ $min[0] = chr(0x80);\r
+ }\r
+\r
+ return array(\r
+ 'min' => new Math_BigInteger($min, 256),\r
+ 'max' => new Math_BigInteger($max, 256)\r
+ );\r
+ }\r
+\r
+ /**\r
+ * DER-decode the length\r
+ *\r
+ * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See\r
+ * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.\r
+ *\r
+ * @access private\r
+ * @param String $string\r
+ * @return Integer\r
+ */\r
+ function _decodeLength(&$string)\r
+ {\r
+ $length = ord($this->_string_shift($string));\r
+ if ( $length & 0x80 ) { // definite length, long form\r
+ $length&= 0x7F;\r
+ $temp = $this->_string_shift($string, $length);\r
+ list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));\r
+ }\r
+ return $length;\r
+ }\r
+\r
+ /**\r
+ * DER-encode the length\r
+ *\r
+ * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See\r
+ * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.\r
+ *\r
+ * @access private\r
+ * @param Integer $length\r
+ * @return String\r
+ */\r
+ function _encodeLength($length)\r
+ {\r
+ if ($length <= 0x7F) {\r
+ return chr($length);\r
+ }\r
+\r
+ $temp = ltrim(pack('N', $length), chr(0));\r
+ return pack('Ca*', 0x80 | strlen($temp), $temp);\r
+ }\r
+\r
+ /**\r
+ * String Shift\r
+ *\r
+ * Inspired by array_shift\r
+ *\r
+ * @param String $string\r
+ * @param optional Integer $index\r
+ * @return String\r
+ * @access private\r
+ */\r
+ function _string_shift(&$string, $index = 1)\r
+ {\r
+ $substr = substr($string, 0, $index);\r
+ $string = substr($string, $index);\r
+ return $substr;\r
+ }\r
+\r
+ /**\r
+ * Determines the private key format\r
+ *\r
+ * @see createKey()\r
+ * @access public\r
+ * @param Integer $format\r
+ */\r
+ function setPrivateKeyFormat($format)\r
+ {\r
+ $this->privateKeyFormat = $format;\r
+ }\r
+\r
+ /**\r
+ * Determines the public key format\r
+ *\r
+ * @see createKey()\r
+ * @access public\r
+ * @param Integer $format\r
+ */\r
+ function setPublicKeyFormat($format)\r
+ {\r
+ $this->publicKeyFormat = $format;\r
+ }\r
+\r
+ /**\r
+ * Determines which hashing function should be used\r
+ *\r
+ * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and\r
+ * decryption. If $hash isn't supported, sha1 is used.\r
+ *\r
+ * @access public\r
+ * @param String $hash\r
+ */\r
+ function setHash($hash)\r
+ {\r
+ // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.\r
+ switch ($hash) {\r
+ case 'md2':\r
+ case 'md5':\r
+ case 'sha1':\r
+ case 'sha256':\r
+ case 'sha384':\r
+ case 'sha512':\r
+ $this->hash = new Crypt_Hash($hash);\r
+ $this->hashName = $hash;\r
+ break;\r
+ default:\r
+ $this->hash = new Crypt_Hash('sha1');\r
+ $this->hashName = 'sha1';\r
+ }\r
+ $this->hLen = $this->hash->getLength();\r
+ }\r
+\r
+ /**\r
+ * Determines which hashing function should be used for the mask generation function\r
+ *\r
+ * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's\r
+ * best if Hash and MGFHash are set to the same thing this is not a requirement.\r
+ *\r
+ * @access public\r
+ * @param String $hash\r
+ */\r
+ function setMGFHash($hash)\r
+ {\r
+ // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.\r
+ switch ($hash) {\r
+ case 'md2':\r
+ case 'md5':\r
+ case 'sha1':\r
+ case 'sha256':\r
+ case 'sha384':\r
+ case 'sha512':\r
+ $this->mgfHash = new Crypt_Hash($hash);\r
+ break;\r
+ default:\r
+ $this->mgfHash = new Crypt_Hash('sha1');\r
+ }\r
+ $this->mgfHLen = $this->mgfHash->getLength();\r
+ }\r
+\r
+ /**\r
+ * Determines the salt length\r
+ *\r
+ * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:\r
+ *\r
+ * Typical salt lengths in octets are hLen (the length of the output\r
+ * of the hash function Hash) and 0.\r
+ *\r
+ * @access public\r
+ * @param Integer $format\r
+ */\r
+ function setSaltLength($sLen)\r
+ {\r
+ $this->sLen = $sLen;\r
+ }\r
+\r
+ /**\r
+ * Generates a random string x bytes long\r
+ *\r
+ * @access public\r
+ * @param Integer $bytes\r
+ * @param optional Integer $nonzero\r
+ * @return String\r
+ */\r
+ function _random($bytes, $nonzero = false)\r
+ {\r
+ $temp = '';\r
+ if ($nonzero) {\r
+ for ($i = 0; $i < $bytes; $i++) {\r
+ $temp.= chr(crypt_random(1, 255));\r
+ }\r
+ } else {\r
+ $ints = ($bytes + 1) >> 2;\r
+ for ($i = 0; $i < $ints; $i++) {\r
+ $temp.= pack('N', crypt_random());\r
+ }\r
+ $temp = substr($temp, 0, $bytes);\r
+ }\r
+ return $temp;\r
+ }\r
+\r
+ /**\r
+ * Integer-to-Octet-String primitive\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $x\r
+ * @param Integer $xLen\r
+ * @return String\r
+ */\r
+ function _i2osp($x, $xLen)\r
+ {\r
+ $x = $x->toBytes();\r
+ if (strlen($x) > $xLen) {\r
+ user_error('Integer too large', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);\r
+ }\r
+\r
+ /**\r
+ * Octet-String-to-Integer primitive\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.\r
+ *\r
+ * @access private\r
+ * @param String $x\r
+ * @return Math_BigInteger\r
+ */\r
+ function _os2ip($x)\r
+ {\r
+ return new Math_BigInteger($x, 256);\r
+ }\r
+\r
+ /**\r
+ * Exponentiate with or without Chinese Remainder Theorem\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $x\r
+ * @return Math_BigInteger\r
+ */\r
+ function _exponentiate($x)\r
+ {\r
+ if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {\r
+ return $x->modPow($this->exponent, $this->modulus);\r
+ }\r
+\r
+ $num_primes = count($this->primes);\r
+\r
+ if (defined('CRYPT_RSA_DISABLE_BLINDING')) {\r
+ $m_i = array(\r
+ 1 => $x->modPow($this->exponents[1], $this->primes[1]),\r
+ 2 => $x->modPow($this->exponents[2], $this->primes[2])\r
+ );\r
+ $h = $m_i[1]->subtract($m_i[2]);\r
+ $h = $h->multiply($this->coefficients[2]);\r
+ list(, $h) = $h->divide($this->primes[1]);\r
+ $m = $m_i[2]->add($h->multiply($this->primes[2]));\r
+\r
+ $r = $this->primes[1];\r
+ for ($i = 3; $i <= $num_primes; $i++) {\r
+ $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);\r
+\r
+ $r = $r->multiply($this->primes[$i - 1]);\r
+\r
+ $h = $m_i->subtract($m);\r
+ $h = $h->multiply($this->coefficients[$i]);\r
+ list(, $h) = $h->divide($this->primes[$i]);\r
+\r
+ $m = $m->add($r->multiply($h));\r
+ }\r
+ } else {\r
+ $smallest = $this->primes[1];\r
+ for ($i = 2; $i <= $num_primes; $i++) {\r
+ if ($smallest->compare($this->primes[$i]) > 0) {\r
+ $smallest = $this->primes[$i];\r
+ }\r
+ }\r
+\r
+ $one = new Math_BigInteger(1);\r
+ $one->setRandomGenerator('crypt_random');\r
+\r
+ $r = $one->random($one, $smallest->subtract($one));\r
+\r
+ $m_i = array(\r
+ 1 => $this->_blind($x, $r, 1),\r
+ 2 => $this->_blind($x, $r, 2)\r
+ );\r
+ $h = $m_i[1]->subtract($m_i[2]);\r
+ $h = $h->multiply($this->coefficients[2]);\r
+ list(, $h) = $h->divide($this->primes[1]);\r
+ $m = $m_i[2]->add($h->multiply($this->primes[2]));\r
+\r
+ $r = $this->primes[1];\r
+ for ($i = 3; $i <= $num_primes; $i++) {\r
+ $m_i = $this->_blind($x, $r, $i);\r
+\r
+ $r = $r->multiply($this->primes[$i - 1]);\r
+\r
+ $h = $m_i->subtract($m);\r
+ $h = $h->multiply($this->coefficients[$i]);\r
+ list(, $h) = $h->divide($this->primes[$i]);\r
+\r
+ $m = $m->add($r->multiply($h));\r
+ }\r
+ }\r
+\r
+ return $m;\r
+ }\r
+\r
+ /**\r
+ * Performs RSA Blinding\r
+ *\r
+ * Protects against timing attacks by employing RSA Blinding.\r
+ * Returns $x->modPow($this->exponents[$i], $this->primes[$i])\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $x\r
+ * @param Math_BigInteger $r\r
+ * @param Integer $i\r
+ * @return Math_BigInteger\r
+ */\r
+ function _blind($x, $r, $i)\r
+ {\r
+ $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));\r
+\r
+ $x = $x->modPow($this->exponents[$i], $this->primes[$i]);\r
+\r
+ $r = $r->modInverse($this->primes[$i]);\r
+ $x = $x->multiply($r);\r
+ list(, $x) = $x->divide($this->primes[$i]);\r
+\r
+ return $x;\r
+ }\r
+\r
+ /**\r
+ * RSAEP\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $m\r
+ * @return Math_BigInteger\r
+ */\r
+ function _rsaep($m)\r
+ {\r
+ if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {\r
+ user_error('Message representative out of range', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ return $this->_exponentiate($m);\r
+ }\r
+\r
+ /**\r
+ * RSADP\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $c\r
+ * @return Math_BigInteger\r
+ */\r
+ function _rsadp($c)\r
+ {\r
+ if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {\r
+ user_error('Ciphertext representative out of range', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ return $this->_exponentiate($c);\r
+ }\r
+\r
+ /**\r
+ * RSASP1\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $m\r
+ * @return Math_BigInteger\r
+ */\r
+ function _rsasp1($m)\r
+ {\r
+ if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {\r
+ user_error('Message representative out of range', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ return $this->_exponentiate($m);\r
+ }\r
+\r
+ /**\r
+ * RSAVP1\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.\r
+ *\r
+ * @access private\r
+ * @param Math_BigInteger $s\r
+ * @return Math_BigInteger\r
+ */\r
+ function _rsavp1($s)\r
+ {\r
+ if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {\r
+ user_error('Signature representative out of range', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ return $this->_exponentiate($s);\r
+ }\r
+\r
+ /**\r
+ * MGF1\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.\r
+ *\r
+ * @access private\r
+ * @param String $mgfSeed\r
+ * @param Integer $mgfLen\r
+ * @return String\r
+ */\r
+ function _mgf1($mgfSeed, $maskLen)\r
+ {\r
+ // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.\r
+\r
+ $t = '';\r
+ $count = ceil($maskLen / $this->mgfHLen);\r
+ for ($i = 0; $i < $count; $i++) {\r
+ $c = pack('N', $i);\r
+ $t.= $this->mgfHash->hash($mgfSeed . $c);\r
+ }\r
+\r
+ return substr($t, 0, $maskLen);\r
+ }\r
+\r
+ /**\r
+ * RSAES-OAEP-ENCRYPT\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and\r
+ * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @param String $l\r
+ * @return String\r
+ */\r
+ function _rsaes_oaep_encrypt($m, $l = '')\r
+ {\r
+ $mLen = strlen($m);\r
+\r
+ // Length checking\r
+\r
+ // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error\r
+ // be output.\r
+\r
+ if ($mLen > $this->k - 2 * $this->hLen - 2) {\r
+ user_error('Message too long', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // EME-OAEP encoding\r
+\r
+ $lHash = $this->hash->hash($l);\r
+ $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);\r
+ $db = $lHash . $ps . chr(1) . $m;\r
+ $seed = $this->_random($this->hLen);\r
+ $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);\r
+ $maskedDB = $db ^ $dbMask;\r
+ $seedMask = $this->_mgf1($maskedDB, $this->hLen);\r
+ $maskedSeed = $seed ^ $seedMask;\r
+ $em = chr(0) . $maskedSeed . $maskedDB;\r
+\r
+ // RSA encryption\r
+\r
+ $m = $this->_os2ip($em);\r
+ $c = $this->_rsaep($m);\r
+ $c = $this->_i2osp($c, $this->k);\r
+\r
+ // Output the ciphertext C\r
+\r
+ return $c;\r
+ }\r
+\r
+ /**\r
+ * RSAES-OAEP-DECRYPT\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error\r
+ * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:\r
+ * \r
+ * Note. Care must be taken to ensure that an opponent cannot\r
+ * distinguish the different error conditions in Step 3.g, whether by\r
+ * error message or timing, or, more generally, learn partial\r
+ * information about the encoded message EM. Otherwise an opponent may\r
+ * be able to obtain useful information about the decryption of the\r
+ * ciphertext C, leading to a chosen-ciphertext attack such as the one\r
+ * observed by Manger [36].\r
+ *\r
+ * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:\r
+ *\r
+ * Both the encryption and the decryption operations of RSAES-OAEP take\r
+ * the value of a label L as input. In this version of PKCS #1, L is\r
+ * the empty string; other uses of the label are outside the scope of\r
+ * this document.\r
+ *\r
+ * @access private\r
+ * @param String $c\r
+ * @param String $l\r
+ * @return String\r
+ */\r
+ function _rsaes_oaep_decrypt($c, $l = '')\r
+ {\r
+ // Length checking\r
+\r
+ // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error\r
+ // be output.\r
+\r
+ if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // RSA decryption\r
+\r
+ $c = $this->_os2ip($c);\r
+ $m = $this->_rsadp($c);\r
+ if ($m === false) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ $em = $this->_i2osp($m, $this->k);\r
+\r
+ // EME-OAEP decoding\r
+\r
+ $lHash = $this->hash->hash($l);\r
+ $y = ord($em[0]);\r
+ $maskedSeed = substr($em, 1, $this->hLen);\r
+ $maskedDB = substr($em, $this->hLen + 1);\r
+ $seedMask = $this->_mgf1($maskedDB, $this->hLen);\r
+ $seed = $maskedSeed ^ $seedMask;\r
+ $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);\r
+ $db = $maskedDB ^ $dbMask;\r
+ $lHash2 = substr($db, 0, $this->hLen);\r
+ $m = substr($db, $this->hLen);\r
+ if ($lHash != $lHash2) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ $m = ltrim($m, chr(0));\r
+ if (ord($m[0]) != 1) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // Output the message M\r
+\r
+ return substr($m, 1);\r
+ }\r
+\r
+ /**\r
+ * RSAES-PKCS1-V1_5-ENCRYPT\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @return String\r
+ */\r
+ function _rsaes_pkcs1_v1_5_encrypt($m)\r
+ {\r
+ $mLen = strlen($m);\r
+\r
+ // Length checking\r
+\r
+ if ($mLen > $this->k - 11) {\r
+ user_error('Message too long', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // EME-PKCS1-v1_5 encoding\r
+\r
+ $ps = $this->_random($this->k - $mLen - 3, true);\r
+ $em = chr(0) . chr(2) . $ps . chr(0) . $m;\r
+\r
+ // RSA encryption\r
+ $m = $this->_os2ip($em);\r
+ $c = $this->_rsaep($m);\r
+ $c = $this->_i2osp($c, $this->k);\r
+\r
+ // Output the ciphertext C\r
+\r
+ return $c;\r
+ }\r
+\r
+ /**\r
+ * RSAES-PKCS1-V1_5-DECRYPT\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.\r
+ *\r
+ * For compatability purposes, this function departs slightly from the description given in RFC3447.\r
+ * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the\r
+ * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the\r
+ * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed\r
+ * to be 2 regardless of which key is used. for compatability purposes, we'll just check to make sure the\r
+ * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.\r
+ *\r
+ * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt\r
+ * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but\r
+ * not private key encrypted ciphertext's.\r
+ *\r
+ * @access private\r
+ * @param String $c\r
+ * @return String\r
+ */\r
+ function _rsaes_pkcs1_v1_5_decrypt($c)\r
+ {\r
+ // Length checking\r
+\r
+ if (strlen($c) != $this->k) { // or if k < 11\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // RSA decryption\r
+\r
+ $c = $this->_os2ip($c);\r
+ $m = $this->_rsadp($c);\r
+ if ($m === false) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ $em = $this->_i2osp($m, $this->k);\r
+\r
+ // EME-PKCS1-v1_5 decoding\r
+\r
+ if (ord($em[0]) != 0 || ord($em[1]) > 2) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);\r
+ $m = substr($em, strlen($ps) + 3);\r
+\r
+ if (strlen($ps) < 8) {\r
+ user_error('Decryption error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // Output M\r
+\r
+ return $m;\r
+ }\r
+\r
+ /**\r
+ * EMSA-PSS-ENCODE\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @param Integer $emBits\r
+ */\r
+ function _emsa_pss_encode($m, $emBits)\r
+ {\r
+ // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error\r
+ // be output.\r
+\r
+ $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)\r
+ $sLen = $this->sLen == false ? $this->hLen : $this->sLen;\r
+\r
+ $mHash = $this->hash->hash($m);\r
+ if ($emLen < $this->hLen + $sLen + 2) {\r
+ user_error('Encoding error', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ $salt = $this->_random($sLen);\r
+ $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;\r
+ $h = $this->hash->hash($m2);\r
+ $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);\r
+ $db = $ps . chr(1) . $salt;\r
+ $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);\r
+ $maskedDB = $db ^ $dbMask;\r
+ $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];\r
+ $em = $maskedDB . $h . chr(0xBC);\r
+\r
+ return $em;\r
+ }\r
+\r
+ /**\r
+ * EMSA-PSS-VERIFY\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @param String $em\r
+ * @param Integer $emBits\r
+ * @return String\r
+ */\r
+ function _emsa_pss_verify($m, $em, $emBits)\r
+ {\r
+ // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error\r
+ // be output.\r
+\r
+ $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);\r
+ $sLen = $this->sLen == false ? $this->hLen : $this->sLen;\r
+\r
+ $mHash = $this->hash->hash($m);\r
+ if ($emLen < $this->hLen + $sLen + 2) {\r
+ return false;\r
+ }\r
+\r
+ if ($em[strlen($em) - 1] != chr(0xBC)) {\r
+ return false;\r
+ }\r
+\r
+ $maskedDB = substr($em, 0, $em - $this->hLen - 1);\r
+ $h = substr($em, $em - $this->hLen - 1, $this->hLen);\r
+ $temp = chr(0xFF << ($emBits & 7));\r
+ if ((~$maskedDB[0] & $temp) != $temp) {\r
+ return false;\r
+ }\r
+ $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);\r
+ $db = $maskedDB ^ $dbMask;\r
+ $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];\r
+ $temp = $emLen - $this->hLen - $sLen - 2;\r
+ if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {\r
+ return false;\r
+ }\r
+ $salt = substr($db, $temp + 1); // should be $sLen long\r
+ $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;\r
+ $h2 = $this->hash->hash($m2);\r
+ return $h == $h2;\r
+ }\r
+\r
+ /**\r
+ * RSASSA-PSS-SIGN\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @return String\r
+ */\r
+ function _rsassa_pss_sign($m)\r
+ {\r
+ // EMSA-PSS encoding\r
+\r
+ $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);\r
+\r
+ // RSA signature\r
+\r
+ $m = $this->_os2ip($em);\r
+ $s = $this->_rsasp1($m);\r
+ $s = $this->_i2osp($s, $this->k);\r
+\r
+ // Output the signature S\r
+\r
+ return $s;\r
+ }\r
+\r
+ /**\r
+ * RSASSA-PSS-VERIFY\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @param String $s\r
+ * @return String\r
+ */\r
+ function _rsassa_pss_verify($m, $s)\r
+ {\r
+ // Length checking\r
+\r
+ if (strlen($s) != $this->k) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // RSA verification\r
+\r
+ $modBits = 8 * $this->k;\r
+\r
+ $s2 = $this->_os2ip($s);\r
+ $m2 = $this->_rsavp1($s2);\r
+ if ($m2 === false) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ $em = $this->_i2osp($m2, $modBits >> 3);\r
+ if ($em === false) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // EMSA-PSS verification\r
+\r
+ return $this->_emsa_pss_verify($m, $em, $modBits - 1);\r
+ }\r
+\r
+ /**\r
+ * EMSA-PKCS1-V1_5-ENCODE\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @param Integer $emLen\r
+ * @return String\r
+ */\r
+ function _emsa_pkcs1_v1_5_encode($m, $emLen)\r
+ {\r
+ $h = $this->hash->hash($m);\r
+ if ($h === false) {\r
+ return false;\r
+ }\r
+\r
+ // see http://tools.ietf.org/html/rfc3447#page-43\r
+ switch ($this->hashName) {\r
+ case 'md2':\r
+ $t = pack('H*', '3020300c06082a864886f70d020205000410');\r
+ break;\r
+ case 'md5':\r
+ $t = pack('H*', '3020300c06082a864886f70d020505000410');\r
+ break;\r
+ case 'sha1':\r
+ $t = pack('H*', '3021300906052b0e03021a05000414');\r
+ break;\r
+ case 'sha256':\r
+ $t = pack('H*', '3031300d060960864801650304020105000420');\r
+ break;\r
+ case 'sha384':\r
+ $t = pack('H*', '3041300d060960864801650304020205000430');\r
+ break;\r
+ case 'sha512':\r
+ $t = pack('H*', '3051300d060960864801650304020305000440');\r
+ }\r
+ $t.= $h;\r
+ $tLen = strlen($t);\r
+\r
+ if ($emLen < $tLen + 11) {\r
+ user_error('Intended encoded message length too short', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);\r
+\r
+ $em = "\0\1$ps\0$t";\r
+\r
+ return $em;\r
+ }\r
+\r
+ /**\r
+ * RSASSA-PKCS1-V1_5-SIGN\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @return String\r
+ */\r
+ function _rsassa_pkcs1_v1_5_sign($m)\r
+ {\r
+ // EMSA-PKCS1-v1_5 encoding\r
+\r
+ $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);\r
+ if ($em === false) {\r
+ user_error('RSA modulus too short', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // RSA signature\r
+\r
+ $m = $this->_os2ip($em);\r
+ $s = $this->_rsasp1($m);\r
+ $s = $this->_i2osp($s, $this->k);\r
+\r
+ // Output the signature S\r
+\r
+ return $s;\r
+ }\r
+\r
+ /**\r
+ * RSASSA-PKCS1-V1_5-VERIFY\r
+ *\r
+ * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.\r
+ *\r
+ * @access private\r
+ * @param String $m\r
+ * @return String\r
+ */\r
+ function _rsassa_pkcs1_v1_5_verify($m, $s)\r
+ {\r
+ // Length checking\r
+\r
+ if (strlen($s) != $this->k) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // RSA verification\r
+\r
+ $s = $this->_os2ip($s);\r
+ $m2 = $this->_rsavp1($s);\r
+ if ($m2 === false) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+ $em = $this->_i2osp($m2, $this->k);\r
+ if ($em === false) {\r
+ user_error('Invalid signature', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // EMSA-PKCS1-v1_5 encoding\r
+\r
+ $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);\r
+ if ($em2 === false) {\r
+ user_error('RSA modulus too short', E_USER_NOTICE);\r
+ return false;\r
+ }\r
+\r
+ // Compare\r
+\r
+ return $em === $em2;\r
+ }\r
+\r
+ /**\r
+ * Set Encryption Mode\r
+ *\r
+ * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.\r
+ *\r
+ * @access public\r
+ * @param Integer $mode\r
+ */\r
+ function setEncryptionMode($mode)\r
+ {\r
+ $this->encryptionMode = $mode;\r
+ }\r
+\r
+ /**\r
+ * Set Signature Mode\r
+ *\r
+ * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1\r
+ *\r
+ * @access public\r
+ * @param Integer $mode\r
+ */\r
+ function setSignatureMode($mode)\r
+ {\r
+ $this->signatureMode = $mode;\r
+ }\r
+\r
+ /**\r
+ * Encryption\r
+ *\r
+ * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.\r
+ * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will\r
+ * be concatenated together.\r
+ *\r
+ * @see decrypt()\r
+ * @access public\r
+ * @param String $plaintext\r
+ * @return String\r
+ */\r
+ function encrypt($plaintext)\r
+ {\r
+ switch ($this->encryptionMode) {\r
+ case CRYPT_RSA_ENCRYPTION_PKCS1:\r
+ $length = $this->k - 11;\r
+ if ($length <= 0) {\r
+ return false;\r
+ }\r
+\r
+ $plaintext = str_split($plaintext, $length);\r
+ $ciphertext = '';\r
+ foreach ($plaintext as $m) {\r
+ $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);\r
+ }\r
+ return $ciphertext;\r
+ //case CRYPT_RSA_ENCRYPTION_OAEP:\r
+ default:\r
+ $length = $this->k - 2 * $this->hLen - 2;\r
+ if ($length <= 0) {\r
+ return false;\r
+ }\r
+\r
+ $plaintext = str_split($plaintext, $length);\r
+ $ciphertext = '';\r
+ foreach ($plaintext as $m) {\r
+ $ciphertext.= $this->_rsaes_oaep_encrypt($m);\r
+ }\r
+ return $ciphertext;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Decryption\r
+ *\r
+ * @see encrypt()\r
+ * @access public\r
+ * @param String $plaintext\r
+ * @return String\r
+ */\r
+ function decrypt($ciphertext)\r
+ {\r
+ if ($this->k <= 0) {\r
+ return false;\r
+ }\r
+\r
+ $ciphertext = str_split($ciphertext, $this->k);\r
+ $plaintext = '';\r
+\r
+ switch ($this->encryptionMode) {\r
+ case CRYPT_RSA_ENCRYPTION_PKCS1:\r
+ $decrypt = '_rsaes_pkcs1_v1_5_decrypt';\r
+ break;\r
+ //case CRYPT_RSA_ENCRYPTION_OAEP:\r
+ default:\r
+ $decrypt = '_rsaes_oaep_decrypt';\r
+ }\r
+\r
+ foreach ($ciphertext as $c) {\r
+ $temp = $this->$decrypt($c);\r
+ if ($temp === false) {\r
+ return false;\r
+ }\r
+ $plaintext.= $temp;\r
+ }\r
+\r
+ return $plaintext;\r
+ }\r
+\r
+ /**\r
+ * Create a signature\r
+ *\r
+ * @see verify()\r
+ * @access public\r
+ * @param String $message\r
+ * @return String\r
+ */\r
+ function sign($message)\r
+ {\r
+ if (empty($this->modulus) || empty($this->exponent)) {\r
+ return false;\r
+ }\r
+\r
+ switch ($this->signatureMode) {\r
+ case CRYPT_RSA_SIGNATURE_PKCS1:\r
+ return $this->_rsassa_pkcs1_v1_5_sign($message);\r
+ //case CRYPT_RSA_SIGNATURE_PSS:\r
+ default:\r
+ return $this->_rsassa_pss_sign($message);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Verifies a signature\r
+ *\r
+ * @see sign()\r
+ * @access public\r
+ * @param String $message\r
+ * @param String $signature\r
+ * @return Boolean\r
+ */\r
+ function verify($message, $signature)\r
+ {\r
+ if (empty($this->modulus) || empty($this->exponent)) {\r
+ return false;\r
+ }\r
+\r
+ switch ($this->signatureMode) {\r
+ case CRYPT_RSA_SIGNATURE_PKCS1:\r
+ return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);\r
+ //case CRYPT_RSA_SIGNATURE_PSS:\r
+ default:\r
+ return $this->_rsassa_pss_verify($message, $signature);\r
+ }\r
+ }\r
+}
\ No newline at end of file