Guest User

RSA

a guest
Feb 29th, 2020
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 98.06 KB | None | 0 0
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3.  
  4. /**
  5.  * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  6.  *
  7.  * PHP versions 4 and 5
  8.  *
  9.  * Here's an example of how to encrypt and decrypt text with this library:
  10.  * <code>
  11.  * <?php
  12.  *    include('Crypt/RSA.php');
  13.  *
  14.  *    $rsa = new Crypt_RSA();
  15.  *    extract($rsa->createKey());
  16.  *
  17.  *    $plaintext = 'terrafrost';
  18.  *
  19.  *    $rsa->loadKey($privatekey);
  20.  *    $ciphertext = $rsa->encrypt($plaintext);
  21.  *
  22.  *    $rsa->loadKey($publickey);
  23.  *    echo $rsa->decrypt($ciphertext);
  24.  * ?>
  25.  * </code>
  26.  *
  27.  * Here's an example of how to create signatures and verify signatures with this library:
  28.  * <code>
  29.  * <?php
  30.  *    include('Crypt/RSA.php');
  31.  *
  32.  *    $rsa = new Crypt_RSA();
  33.  *    extract($rsa->createKey());
  34.  *
  35.  *    $plaintext = 'terrafrost';
  36.  *
  37.  *    $rsa->loadKey($privatekey);
  38.  *    $signature = $rsa->sign($plaintext);
  39.  *
  40.  *    $rsa->loadKey($publickey);
  41.  *    echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
  42.  * ?>
  43.  * </code>
  44.  *
  45.  * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  46.  * of this software and associated documentation files (the "Software"), to deal
  47.  * in the Software without restriction, including without limitation the rights
  48.  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  49.  * copies of the Software, and to permit persons to whom the Software is
  50.  * furnished to do so, subject to the following conditions:
  51.  *
  52.  * The above copyright notice and this permission notice shall be included in
  53.  * all copies or substantial portions of the Software.
  54.  *
  55.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  56.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  57.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  58.  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  59.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  60.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  61.  * THE SOFTWARE.
  62.  *
  63.  * @category   Crypt
  64.  * @package    Crypt_RSA
  65.  * @author     Jim Wigginton <terrafrost@php.net>
  66.  * @copyright  MMIX Jim Wigginton
  67.  * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
  68.  * @link       http://phpseclib.sourceforge.net
  69.  */
  70.  
  71. /**
  72.  * Include Crypt_Random
  73.  */
  74. // the class_exists() will only be called if the crypt_random_string function hasn't been defined and
  75. // will trigger a call to __autoload() if you're wanting to auto-load classes
  76. // call function_exists() a second time to stop the require_once from being called outside
  77. // of the auto loader
  78. if (!function_exists('crypt_random_string')) {
  79.     require_once('Random.php');
  80. }
  81.  
  82. /**
  83.  * Include Crypt_Hash
  84.  */
  85. if (!class_exists('Crypt_Hash')) {
  86.     require_once('Hash.php');
  87. }
  88.  
  89. /**#@+
  90.  * @access public
  91.  * @see Crypt_RSA::encrypt()
  92.  * @see Crypt_RSA::decrypt()
  93.  */
  94. /**
  95.  * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  96.  * (OAEP) for encryption / decryption.
  97.  *
  98.  * Uses sha1 by default.
  99.  *
  100.  * @see Crypt_RSA::setHash()
  101.  * @see Crypt_RSA::setMGFHash()
  102.  */
  103. define('CRYPT_RSA_ENCRYPTION_OAEP',  1);
  104. /**
  105.  * Use PKCS#1 padding.
  106.  *
  107.  * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  108.  * compatability with protocols (like SSH-1) written before OAEP's introduction.
  109.  */
  110. define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
  111. /**#@-*/
  112.  
  113. /**#@+
  114.  * @access public
  115.  * @see Crypt_RSA::sign()
  116.  * @see Crypt_RSA::verify()
  117.  * @see Crypt_RSA::setHash()
  118.  */
  119. /**
  120.  * Use the Probabilistic Signature Scheme for signing
  121.  *
  122.  * Uses sha1 by default.
  123.  *
  124.  * @see Crypt_RSA::setSaltLength()
  125.  * @see Crypt_RSA::setMGFHash()
  126.  */
  127. define('CRYPT_RSA_SIGNATURE_PSS',  1);
  128. /**
  129.  * Use the PKCS#1 scheme by default.
  130.  *
  131.  * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  132.  * compatability with protocols (like SSH-2) written before PSS's introduction.
  133.  */
  134. define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
  135. /**#@-*/
  136.  
  137. /**#@+
  138.  * @access private
  139.  * @see Crypt_RSA::createKey()
  140.  */
  141. /**
  142.  * ASN1 Integer
  143.  */
  144. define('CRYPT_RSA_ASN1_INTEGER',   2);
  145. /**
  146.  * ASN1 Bit String
  147.  */
  148. define('CRYPT_RSA_ASN1_BITSTRING', 3);
  149. /**
  150.  * ASN1 Sequence (with the constucted bit set)
  151.  */
  152. define('CRYPT_RSA_ASN1_SEQUENCE', 48);
  153. /**#@-*/
  154.  
  155. /**#@+
  156.  * @access private
  157.  * @see Crypt_RSA::Crypt_RSA()
  158.  */
  159. /**
  160.  * To use the pure-PHP implementation
  161.  */
  162. define('CRYPT_RSA_MODE_INTERNAL', 1);
  163. /**
  164.  * To use the OpenSSL library
  165.  *
  166.  * (if enabled; otherwise, the internal implementation will be used)
  167.  */
  168. define('CRYPT_RSA_MODE_OPENSSL', 2);
  169. /**#@-*/
  170.  
  171. /**
  172.  * Default openSSL configuration file.
  173.  */
  174. define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/../openssl.cnf');
  175.  
  176.  
  177. /**#@+
  178.  * @access public
  179.  * @see Crypt_RSA::createKey()
  180.  * @see Crypt_RSA::setPrivateKeyFormat()
  181.  */
  182. /**
  183.  * PKCS#1 formatted private key
  184.  *
  185.  * Used by OpenSSH
  186.  */
  187. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
  188. /**
  189.  * PuTTY formatted private key
  190.  */
  191. define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
  192. /**
  193.  * XML formatted private key
  194.  */
  195. define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
  196. /**#@-*/
  197.  
  198. /**#@+
  199.  * @access public
  200.  * @see Crypt_RSA::createKey()
  201.  * @see Crypt_RSA::setPublicKeyFormat()
  202.  */
  203. /**
  204.  * Raw public key
  205.  *
  206.  * An array containing two Math_BigInteger objects.
  207.  *
  208.  * The exponent can be indexed with any of the following:
  209.  *
  210.  * 0, e, exponent, publicExponent
  211.  *
  212.  * The modulus can be indexed with any of the following:
  213.  *
  214.  * 1, n, modulo, modulus
  215.  */
  216. define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
  217. /**
  218.  * PKCS#1 formatted public key (raw)
  219.  *
  220.  * Used by File/X509.php
  221.  */
  222. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
  223. /**
  224.  * XML formatted public key
  225.  */
  226. define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
  227. /**
  228.  * OpenSSH formatted public key
  229.  *
  230.  * Place in $HOME/.ssh/authorized_keys
  231.  */
  232. define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
  233. /**
  234.  * PKCS#1 formatted public key (encapsulated)
  235.  *
  236.  * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
  237.  */
  238. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 7);
  239. /**#@-*/
  240.  
  241. /**
  242.  * MultiPrimeNotSupportedException
  243.  *
  244.  * @author  Jim Wigginton <terrafrost@php.net>
  245.  * @version 0.3.5
  246.  * @access  public
  247.  * @package Crypt_RSA
  248.  */
  249. class MultiPrimeNotSupportedException extends Exception {}
  250.  
  251. /**
  252.  * FormatNotSupportedException
  253.  *
  254.  * @author  Jim Wigginton <terrafrost@php.net>
  255.  * @version 0.3.5
  256.  * @access  public
  257.  * @package Crypt_RSA
  258.  */
  259. class FormatNotSupportedException extends Exception {}
  260.  
  261. /**
  262.  * KeyNotLoadedException
  263.  *
  264.  * @author  Jim Wigginton <terrafrost@php.net>
  265.  * @version 0.3.5
  266.  * @access  public
  267.  * @package Crypt_RSA
  268.  */
  269. class KeyNotLoadedException extends Exception {}
  270.  
  271. /**
  272.  * EncryptionException
  273.  *
  274.  * @author  Jim Wigginton <terrafrost@php.net>
  275.  * @version 0.3.5
  276.  * @access  public
  277.  * @package Crypt_RSA
  278.  */
  279. class EncryptionException extends Exception {}
  280.  
  281. /**
  282.  * DecryptionException
  283.  *
  284.  * @author  Jim Wigginton <terrafrost@php.net>
  285.  * @version 0.3.5
  286.  * @access  public
  287.  * @package Crypt_RSA
  288.  */
  289. class DecryptionException extends Exception {}
  290.  
  291. /**
  292.  * SigningException
  293.  *
  294.  * @author  Jim Wigginton <terrafrost@php.net>
  295.  * @version 0.3.5
  296.  * @access  public
  297.  * @package Crypt_RSA
  298.  */
  299. class SigningException extends Exception {}
  300.  
  301. /**
  302.  * VerificationException
  303.  *
  304.  * @author  Jim Wigginton <terrafrost@php.net>
  305.  * @version 0.3.5
  306.  * @access  public
  307.  * @package Crypt_RSA
  308.  */
  309. class VerificationException extends Exception {}
  310.  
  311. /**
  312.  * EncodingException
  313.  *
  314.  * @author  Jim Wigginton <terrafrost@php.net>
  315.  * @version 0.3.5
  316.  * @access  public
  317.  * @package Crypt_RSA
  318.  */
  319. class EncodingException extends Exception {}
  320.  
  321. /**
  322.  * BadPasswordException
  323.  *
  324.  * @author  Jim Wigginton <terrafrost@php.net>
  325.  * @version 0.3.5
  326.  * @access  public
  327.  * @package Crypt_RSA
  328.  */
  329. class BadPasswordException extends Exception {}
  330.  
  331. /**
  332.  * Pure-PHP PKCS#1 compliant implementation of RSA.
  333.  *
  334.  * @author  Jim Wigginton <terrafrost@php.net>
  335.  * @version 0.1.0
  336.  * @access  public
  337.  * @package Crypt_RSA
  338.  */
  339. class Crypt_RSA {
  340.     /**
  341.      * Precomputed Zero
  342.      *
  343.      * @var Array
  344.      * @access private
  345.      */
  346.     var $zero;
  347.  
  348.     /**
  349.      * Precomputed One
  350.      *
  351.      * @var Array
  352.      * @access private
  353.      */
  354.     var $one;
  355.  
  356.     /**
  357.      * Private Key Format
  358.      *
  359.      * @var Integer
  360.      * @access private
  361.      */
  362.     var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  363.  
  364.     /**
  365.      * Public Key Format
  366.      *
  367.      * @var Integer
  368.      * @access public
  369.      */
  370.     var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
  371.  
  372.     /**
  373.      * Modulus (ie. n)
  374.      *
  375.      * @var Math_BigInteger
  376.      * @access private
  377.      */
  378.     var $modulus;
  379.  
  380.     /**
  381.      * Modulus length
  382.      *
  383.      * @var Math_BigInteger
  384.      * @access private
  385.      */
  386.     var $k;
  387.  
  388.     /**
  389.      * Exponent (ie. e or d)
  390.      *
  391.      * @var Math_BigInteger
  392.      * @access private
  393.      */
  394.     var $exponent;
  395.  
  396.     /**
  397.      * Primes for Chinese Remainder Theorem (ie. p and q)
  398.      *
  399.      * @var Array
  400.      * @access private
  401.      */
  402.     var $primes;
  403.  
  404.     /**
  405.      * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  406.      *
  407.      * @var Array
  408.      * @access private
  409.      */
  410.     var $exponents;
  411.  
  412.     /**
  413.      * Coefficients for Chinese Remainder Theorem (ie. qInv)
  414.      *
  415.      * @var Array
  416.      * @access private
  417.      */
  418.     var $coefficients;
  419.  
  420.     /**
  421.      * Hash name
  422.      *
  423.      * @var String
  424.      * @access private
  425.      */
  426.     var $hashName;
  427.  
  428.     /**
  429.      * Hash function
  430.      *
  431.      * @var Crypt_Hash
  432.      * @access private
  433.      */
  434.     var $hash;
  435.  
  436.     /**
  437.      * Length of hash function output
  438.      *
  439.      * @var Integer
  440.      * @access private
  441.      */
  442.     var $hLen;
  443.  
  444.     /**
  445.      * Length of salt
  446.      *
  447.      * @var Integer
  448.      * @access private
  449.      */
  450.     var $sLen;
  451.  
  452.     /**
  453.      * Hash function for the Mask Generation Function
  454.      *
  455.      * @var Crypt_Hash
  456.      * @access private
  457.      */
  458.     var $mgfHash;
  459.  
  460.     /**
  461.      * Length of MGF hash function output
  462.      *
  463.      * @var Integer
  464.      * @access private
  465.      */
  466.     var $mgfHLen;
  467.  
  468.     /**
  469.      * Encryption mode
  470.      *
  471.      * @var Integer
  472.      * @access private
  473.      */
  474.     var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  475.  
  476.     /**
  477.      * Signature mode
  478.      *
  479.      * @var Integer
  480.      * @access private
  481.      */
  482.     var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  483.  
  484.     /**
  485.      * Public Exponent
  486.      *
  487.      * @var Mixed
  488.      * @access private
  489.      */
  490.     var $publicExponent = false;
  491.  
  492.     /**
  493.      * Password
  494.      *
  495.      * @var String
  496.      * @access private
  497.      */
  498.     var $password = false;
  499.  
  500.     /**
  501.      * Components
  502.      *
  503.      * For use with parsing XML formatted keys.  PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
  504.      * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
  505.      *
  506.      * @see Crypt_RSA::_start_element_handler()
  507.      * @var Array
  508.      * @access private
  509.      */
  510.     var $components = array();
  511.  
  512.     /**
  513.      * Current String
  514.      *
  515.      * For use with parsing XML formatted keys.
  516.      *
  517.      * @see Crypt_RSA::_character_handler()
  518.      * @see Crypt_RSA::_stop_element_handler()
  519.      * @var Mixed
  520.      * @access private
  521.      */
  522.     var $current;
  523.  
  524.     /**
  525.      * OpenSSL configuration file name.
  526.      *
  527.      * Set to NULL to use system configuration file.
  528.      * @see Crypt_RSA::createKey()
  529.      * @var Mixed
  530.      * @Access public
  531.      */
  532.     var $configFile;
  533.  
  534.     /**
  535.      * Public key comment field.
  536.      *
  537.      * @var String
  538.      * @access private
  539.      */
  540.     var $comment = 'phpseclib-generated-key';
  541.  
  542.     /**
  543.      * The constructor
  544.      *
  545.      * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself.  The reason
  546.      * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully.  openssl_pkey_new(), in particular, requires
  547.      * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  548.      *
  549.      * @return Crypt_RSA
  550.      * @access public
  551.      */
  552.     function Crypt_RSA()
  553.     {
  554.         if (!class_exists('Math_BigInteger')) {
  555.             require_once('Math/BigInteger.php');
  556.         }
  557.  
  558.         $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
  559.  
  560.         if ( !defined('CRYPT_RSA_MODE') ) {
  561.             switch (true) {
  562.                 case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
  563.                     define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  564.                     break;
  565.                 default:
  566.                     define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  567.             }
  568.         }
  569.  
  570.         $this->zero = new Math_BigInteger();
  571.         $this->one = new Math_BigInteger(1);
  572.  
  573.         $this->hash = new Crypt_Hash('sha1');
  574.         $this->hLen = $this->hash->getLength();
  575.         $this->hashName = 'sha1';
  576.         $this->mgfHash = new Crypt_Hash('sha1');
  577.         $this->mgfHLen = $this->mgfHash->getLength();
  578.     }
  579.  
  580.     /**
  581.      * Create public / private key pair
  582.      *
  583.      * Returns an array with the following three elements:
  584.      *  - 'privatekey': The private key.
  585.      *  - 'publickey':  The public key.
  586.      *  - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  587.      *                  Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  588.      *
  589.      * @access public
  590.      * @param optional Integer $bits
  591.      * @param optional Integer $timeout
  592.      * @param optional Math_BigInteger $p
  593.      */
  594.     function createKey($bits = 1024, $timeout = false, $partial = array())
  595.     {
  596.         if (!defined('CRYPT_RSA_EXPONENT')) {
  597.             // http://en.wikipedia.org/wiki/65537_%28number%29
  598.             define('CRYPT_RSA_EXPONENT', '65537');
  599.         }
  600.         // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  601.         // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
  602.         // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
  603.         // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
  604.         // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
  605.         // generation when there's a chance neither gmp nor OpenSSL are installed)
  606.         if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  607.             define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  608.         }
  609.  
  610.         // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  611.         if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
  612.             $config = array();
  613.             if (isset($this->configFile)) {
  614.                 $config['config'] = $this->configFile;
  615.             }
  616.             $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
  617.             openssl_pkey_export($rsa, $privatekey, NULL, $config);
  618.             $publickey = openssl_pkey_get_details($rsa);
  619.             $publickey = $publickey['key'];
  620.  
  621.             $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  622.             $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  623.  
  624.             // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  625.             while (openssl_error_string() !== false);
  626.  
  627.             return array(
  628.                 'privatekey' => $privatekey,
  629.                 'publickey' => $publickey,
  630.                 'partialkey' => false
  631.             );
  632.         }
  633.  
  634.         static $e;
  635.         if (!isset($e)) {
  636.             $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
  637.         }
  638.  
  639.         extract($this->_generateMinMax($bits));
  640.         $absoluteMin = $min;
  641.         $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
  642.         if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  643.             $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  644.             $temp = CRYPT_RSA_SMALLEST_PRIME;
  645.         } else {
  646.             $num_primes = 2;
  647.         }
  648.         extract($this->_generateMinMax($temp + $bits % $temp));
  649.         $finalMax = $max;
  650.         extract($this->_generateMinMax($temp));
  651.  
  652.         $generator = new Math_BigInteger();
  653.  
  654.         $n = $this->one->copy();
  655.         if (!empty($partial)) {
  656.             extract(unserialize($partial));
  657.         } else {
  658.             $exponents = $coefficients = $primes = array();
  659.             $lcm = array(
  660.                 'top' => $this->one->copy(),
  661.                 'bottom' => false
  662.             );
  663.         }
  664.  
  665.         $start = time();
  666.         $i0 = count($primes) + 1;
  667.  
  668.         do {
  669.             for ($i = $i0; $i <= $num_primes; $i++) {
  670.                 if ($timeout !== false) {
  671.                     $timeout-= time() - $start;
  672.                     $start = time();
  673.                     if ($timeout <= 0) {
  674.                         return array(
  675.                             'privatekey' => '',
  676.                             'publickey'  => '',
  677.                             'partialkey' => serialize(array(
  678.                                 'primes' => $primes,
  679.                                 'coefficients' => $coefficients,
  680.                                 'lcm' => $lcm,
  681.                                 'exponents' => $exponents
  682.                             ))
  683.                         );
  684.                     }
  685.                 }
  686.  
  687.                 if ($i == $num_primes) {
  688.                     list($min, $temp) = $absoluteMin->divide($n);
  689.                     if (!$temp->equals($this->zero)) {
  690.                         $min = $min->add($this->one); // ie. ceil()
  691.                     }
  692.                     $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  693.                 } else {
  694.                     $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  695.                 }
  696.  
  697.                 if ($primes[$i] === false) { // if we've reached the timeout
  698.                     if (count($primes) > 1) {
  699.                         $partialkey = '';
  700.                     } else {
  701.                         array_pop($primes);
  702.                         $partialkey = serialize(array(
  703.                             'primes' => $primes,
  704.                             'coefficients' => $coefficients,
  705.                             'lcm' => $lcm,
  706.                             'exponents' => $exponents
  707.                         ));
  708.                     }
  709.  
  710.                     return array(
  711.                         'privatekey' => '',
  712.                         'publickey'  => '',
  713.                         'partialkey' => $partialkey
  714.                     );
  715.                 }
  716.  
  717.                 // the first coefficient is calculated differently from the rest
  718.                 // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  719.                 if ($i > 2) {
  720.                     $coefficients[$i] = $n->modInverse($primes[$i]);
  721.                 }
  722.  
  723.                 $n = $n->multiply($primes[$i]);
  724.  
  725.                 $temp = $primes[$i]->subtract($this->one);
  726.  
  727.                 // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  728.                 // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  729.                 $lcm['top'] = $lcm['top']->multiply($temp);
  730.                 $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  731.  
  732.                 $exponents[$i] = $e->modInverse($temp);
  733.             }
  734.  
  735.             list($lcm) = $lcm['top']->divide($lcm['bottom']);
  736.             $gcd = $lcm->gcd($e);
  737.             $i0 = 1;
  738.         } while (!$gcd->equals($this->one));
  739.  
  740.         $d = $e->modInverse($lcm);
  741.  
  742.         $coefficients[2] = $primes[2]->modInverse($primes[1]);
  743.  
  744.         // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  745.         // RSAPrivateKey ::= SEQUENCE {
  746.         //     version           Version,
  747.         //     modulus           INTEGER,  -- n
  748.         //     publicExponent    INTEGER,  -- e
  749.         //     privateExponent   INTEGER,  -- d
  750.         //     prime1            INTEGER,  -- p
  751.         //     prime2            INTEGER,  -- q
  752.         //     exponent1         INTEGER,  -- d mod (p-1)
  753.         //     exponent2         INTEGER,  -- d mod (q-1)
  754.         //     coefficient       INTEGER,  -- (inverse of q) mod p
  755.         //     otherPrimeInfos   OtherPrimeInfos OPTIONAL
  756.         // }
  757.  
  758.         return array(
  759.             'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  760.             'publickey'  => $this->_convertPublicKey($n, $e),
  761.             'partialkey' => false
  762.         );
  763.     }
  764.  
  765.     /**
  766.      * Convert a private key to the appropriate format.
  767.      *
  768.      * @access private
  769.      * @see setPrivateKeyFormat()
  770.      * @param String $RSAPrivateKey
  771.      * @return String
  772.      */
  773.     function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  774.     {
  775.         $num_primes = count($primes);
  776.         $raw = array(
  777.             'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  778.             'modulus' => $n->toBytes(true),
  779.             'publicExponent' => $e->toBytes(true),
  780.             'privateExponent' => $d->toBytes(true),
  781.             'prime1' => $primes[1]->toBytes(true),
  782.             'prime2' => $primes[2]->toBytes(true),
  783.             'exponent1' => $exponents[1]->toBytes(true),
  784.             'exponent2' => $exponents[2]->toBytes(true),
  785.             'coefficient' => $coefficients[2]->toBytes(true)
  786.         );
  787.  
  788.         // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  789.         // call _convertPublicKey() instead.
  790.         switch ($this->privateKeyFormat) {
  791.             case CRYPT_RSA_PRIVATE_FORMAT_XML:
  792.                 if ($num_primes != 2) {
  793.                     throw new MultiPrimeNotSupportedException('Multi-prime RSA is not supported by XML keys');
  794.                 }
  795.                 return "<RSAKeyValue>\r\n" .
  796.                        '  <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
  797.                        '  <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
  798.                        '  <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
  799.                        '  <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
  800.                        '  <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
  801.                        '  <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
  802.                        '  <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
  803.                        '  <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
  804.                        '</RSAKeyValue>';
  805.                 break;
  806.             case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  807.                 if ($num_primes != 2) {
  808.                     throw new MultiPrimeNotSupportedException('Multi-prime RSA is not supported by PuTTY keys');
  809.                 }
  810.                 $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
  811.                 $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
  812.                 $key.= $encryption;
  813.                 $key.= "\r\nComment: " . $this->comment . "\r\n";
  814.                 $public = pack('Na*Na*Na*',
  815.                     strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
  816.                 );
  817.                 $source = pack('Na*Na*Na*Na*',
  818.                               strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
  819.                               strlen($this->comment), $this->comment, strlen($public), $public
  820.                 );
  821.                 $public = base64_encode($public);
  822.                 $key.= "Public-Lines: " . ((strlen($public) + 32) >> 6) . "\r\n";
  823.                 $key.= chunk_split($public, 64);
  824.                 $private = pack('Na*Na*Na*Na*',
  825.                     strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
  826.                     strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
  827.                 );
  828.                 if (empty($this->password) && !is_string($this->password)) {
  829.                     $source.= pack('Na*', strlen($private), $private);
  830.                     $hashkey = 'putty-private-key-file-mac-key';
  831.                 } else {
  832.                     $private.= crypt_random_string(16 - (strlen($private) & 15));
  833.                     $source.= pack('Na*', strlen($private), $private);
  834.                     if (!class_exists('Crypt_AES')) {
  835.                         require_once('Crypt/AES.php');
  836.                     }
  837.                     $sequence = 0;
  838.                     $symkey = '';
  839.                     while (strlen($symkey) < 32) {
  840.                         $temp = pack('Na*', $sequence++, $this->password);
  841.                         $symkey.= pack('H*', sha1($temp));
  842.                     }
  843.                     $symkey = substr($symkey, 0, 32);
  844.                     $crypto = new Crypt_AES();
  845.  
  846.                     $crypto->setKey($symkey);
  847.                     $crypto->disablePadding();
  848.                     $private = $crypto->encrypt($private);
  849.                     $hashkey = 'putty-private-key-file-mac-key' . $this->password;
  850.                 }
  851.  
  852.                 $private = base64_encode($private);
  853.                 $key.= 'Private-Lines: ' . ((strlen($private) + 32) >> 6) . "\r\n";
  854.                 $key.= chunk_split($private, 64);
  855.                 if (!class_exists('Crypt_Hash')) {
  856.                     require_once('Crypt/Hash.php');
  857.                 }
  858.                 $hash = new Crypt_Hash('sha1');
  859.                 $hash->setKey(pack('H*', sha1($hashkey)));
  860.                 $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
  861.  
  862.                 return $key;
  863.             default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  864.                 $components = array();
  865.                 foreach ($raw as $name => $value) {
  866.                     $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  867.                 }
  868.  
  869.                 $RSAPrivateKey = implode('', $components);
  870.  
  871.                 if ($num_primes > 2) {
  872.                     $OtherPrimeInfos = '';
  873.                     for ($i = 3; $i <= $num_primes; $i++) {
  874.                         // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  875.                         //
  876.                         // OtherPrimeInfo ::= SEQUENCE {
  877.                         //     prime             INTEGER,  -- ri
  878.                         //     exponent          INTEGER,  -- di
  879.                         //     coefficient       INTEGER   -- ti
  880.                         // }
  881.                         $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  882.                         $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  883.                         $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  884.                         $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  885.                     }
  886.                     $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  887.                 }
  888.  
  889.                 $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  890.  
  891.                 if (!empty($this->password) || is_string($this->password)) {
  892.                     $iv = crypt_random_string(8);
  893.                     $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  894.                     $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  895.                     if (!class_exists('Crypt_TripleDES')) {
  896.                         require_once('Crypt/TripleDES.php');
  897.                     }
  898.                     $des = new Crypt_TripleDES();
  899.                     $des->setKey($symkey);
  900.                     $des->setIV($iv);
  901.                     $iv = strtoupper(bin2hex($iv));
  902.                     $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  903.                                      "Proc-Type: 4,ENCRYPTED\r\n" .
  904.                                      "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  905.                                      "\r\n" .
  906.                                      chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
  907.                                      '-----END RSA PRIVATE KEY-----';
  908.                 } else {
  909.                     $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  910.                                      chunk_split(base64_encode($RSAPrivateKey), 64) .
  911.                                      '-----END RSA PRIVATE KEY-----';
  912.                 }
  913.  
  914.                 return $RSAPrivateKey;
  915.         }
  916.     }
  917.  
  918.     /**
  919.      * Convert a public key to the appropriate format
  920.      *
  921.      * @access private
  922.      * @see setPublicKeyFormat()
  923.      * @param String $RSAPrivateKey
  924.      * @return String
  925.      */
  926.     function _convertPublicKey($n, $e)
  927.     {
  928.         $modulus = $n->toBytes(true);
  929.         $publicExponent = $e->toBytes(true);
  930.  
  931.         switch ($this->publicKeyFormat) {
  932.             case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  933.                 return array('e' => $e->copy(), 'n' => $n->copy());
  934.             case CRYPT_RSA_PUBLIC_FORMAT_XML:
  935.                 return "<RSAKeyValue>\r\n" .
  936.                        '  <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
  937.                        '  <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
  938.                        '</RSAKeyValue>';
  939.                 break;
  940.             case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  941.                 // from <http://tools.ietf.org/html/rfc4253#page-15>:
  942.                 // string    "ssh-rsa"
  943.                 // mpint     e
  944.                 // mpint     n
  945.                 $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  946.                 $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
  947.  
  948.                 return $RSAPublicKey;
  949.             default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  950.                 // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  951.                 // RSAPublicKey ::= SEQUENCE {
  952.                 //     modulus           INTEGER,  -- n
  953.                 //     publicExponent    INTEGER   -- e
  954.                 // }
  955.                 $components = array(
  956.                     'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  957.                     'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  958.                 );
  959.  
  960.                 $RSAPublicKey = pack('Ca*a*a*',
  961.                     CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  962.                     $components['modulus'], $components['publicExponent']
  963.                 );
  964.  
  965.                 if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1) {
  966.                     // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
  967.                     $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  968.                     $RSAPublicKey = chr(0) . $RSAPublicKey;
  969.                     $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  970.  
  971.                     $RSAPublicKey = pack('Ca*a*',
  972.                         CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
  973.                     );
  974.                 }
  975.  
  976.                 $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  977.                                  chunk_split(base64_encode($RSAPublicKey), 64) .
  978.                                  '-----END PUBLIC KEY-----';
  979.  
  980.                 return $RSAPublicKey;
  981.         }
  982.     }
  983.  
  984.     /**
  985.      * Break a public or private key down into its constituant components
  986.      *
  987.      * @access private
  988.      * @see _convertPublicKey()
  989.      * @see _convertPrivateKey()
  990.      * @param String $key
  991.      * @param Integer $type
  992.      * @return Array
  993.      */
  994.     function _parseKey($key, $type)
  995.     {
  996.         if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
  997.             throw new FormatNotSupportedException('Unable to parse unsupported key format');
  998.         }
  999.  
  1000.         switch ($type) {
  1001.             case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  1002.                 if (!is_array($key)) {
  1003.                     throw new FormatNotSupportedException('Raw: Expected array type');
  1004.                 }
  1005.                 $components = array();
  1006.                 switch (true) {
  1007.                     case isset($key['e']):
  1008.                         $components['publicExponent'] = $key['e']->copy();
  1009.                         break;
  1010.                     case isset($key['exponent']):
  1011.                         $components['publicExponent'] = $key['exponent']->copy();
  1012.                         break;
  1013.                     case isset($key['publicExponent']):
  1014.                         $components['publicExponent'] = $key['publicExponent']->copy();
  1015.                         break;
  1016.                     case isset($key[0]):
  1017.                         $components['publicExponent'] = $key[0]->copy();
  1018.                 }
  1019.                 switch (true) {
  1020.                     case isset($key['n']):
  1021.                         $components['modulus'] = $key['n']->copy();
  1022.                         break;
  1023.                     case isset($key['modulo']):
  1024.                         $components['modulus'] = $key['modulo']->copy();
  1025.                         break;
  1026.                     case isset($key['modulus']):
  1027.                         $components['modulus'] = $key['modulus']->copy();
  1028.                         break;
  1029.                     case isset($key[1]):
  1030.                         $components['modulus'] = $key[1]->copy();
  1031.                 }
  1032.                 return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
  1033.             case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  1034.             case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  1035.                 /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  1036.                    "outside the scope" of PKCS#1.  PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  1037.                    protect private keys, however, that's not what OpenSSL* does.  OpenSSL protects private keys by adding
  1038.                    two new "fields" to the key - DEK-Info and Proc-Type.  These fields are discussed here:
  1039.  
  1040.                    http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  1041.                    http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  1042.  
  1043.                    DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  1044.                    DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  1045.                    function.  As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  1046.                    own implementation.  ie. the implementation *is* the standard and any bugs that may exist in that
  1047.                    implementation are part of the standard, as well.
  1048.  
  1049.                    * OpenSSL is the de facto standard.  It's utilized by OpenSSH and other projects */
  1050.                 $is_encrypted = preg_match('#DEK-Info: (.+),(.+)#', $key, $matches);
  1051.                 if ($is_encrypted) {
  1052.                     $iv = pack('H*', trim($matches[2]));
  1053.                     $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  1054.                     $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
  1055.                     $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-| #s', '', $key);
  1056.                     $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
  1057.                     if ($ciphertext === false) {
  1058.                         $ciphertext = $key;
  1059.                     }
  1060.                     switch ($matches[1]) {
  1061.                         case 'AES-256-CBC':
  1062.                             if (!class_exists('Crypt_AES')) {
  1063.                                 require_once('Crypt/AES.php');
  1064.                             }
  1065.                             $crypto = new Crypt_AES();
  1066.                             break;
  1067.                         case 'AES-128-CBC':
  1068.                             if (!class_exists('Crypt_AES')) {
  1069.                                 require_once('Crypt/AES.php');
  1070.                             }
  1071.                             $symkey = substr($symkey, 0, 16);
  1072.                             $crypto = new Crypt_AES();
  1073.                             break;
  1074.                         case 'DES-EDE3-CFB':
  1075.                             if (!class_exists('Crypt_TripleDES')) {
  1076.                                 require_once('Crypt/TripleDES.php');
  1077.                             }
  1078.                             $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  1079.                             break;
  1080.                         case 'DES-EDE3-CBC':
  1081.                             if (!class_exists('Crypt_TripleDES')) {
  1082.                                 require_once('Crypt/TripleDES.php');
  1083.                             }
  1084.                             $symkey = substr($symkey, 0, 24);
  1085.                             $crypto = new Crypt_TripleDES();
  1086.                             break;
  1087.                         case 'DES-CBC':
  1088.                             if (!class_exists('Crypt_DES')) {
  1089.                                 require_once('Crypt/DES.php');
  1090.                             }
  1091.                             $crypto = new Crypt_DES();
  1092.                             break;
  1093.                         default:
  1094.                             throw new FormatNotSupportedException("PKCS1: $matches[1] is an unsupported cipher");
  1095.                     }
  1096.                     $crypto->setKey($symkey);
  1097.                     $crypto->setIV($iv);
  1098.                     try {
  1099.                         $decoded = $crypto->decrypt($ciphertext);
  1100.                     } catch (InvalidPaddingException $e) {
  1101.                         $decoded = false;
  1102.                     }
  1103.                 } else {
  1104.                     $decoded = preg_replace('#-.+-|[\r\n]| #', '', $key);
  1105.                     $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
  1106.                 }
  1107.  
  1108.                 if ($decoded !== false) {
  1109.                     $key = $decoded;
  1110.                 }
  1111.  
  1112.                 $components = array();
  1113.  
  1114.                 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1115.                     throw $is_encrypted ?
  1116.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1117.                         new FormatNotSupportedException('PKCS1: Expected a SEQUENCE tag');
  1118.                 }
  1119.                 if ($this->_decodeLength($key) != strlen($key)) {
  1120.                     throw $is_encrypted ?
  1121.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1122.                         new FormatNotSupportedException('PKCS1: Tag length does not match key length');
  1123.                 }
  1124.  
  1125.                 $tag = ord($this->_string_shift($key));
  1126.                 /* intended for keys for which OpenSSL's asn1parse returns the following:
  1127.  
  1128.                     0:d=0  hl=4 l= 631 cons: SEQUENCE
  1129.                     4:d=1  hl=2 l=   1 prim:  INTEGER           :00
  1130.                     7:d=1  hl=2 l=  13 cons:  SEQUENCE
  1131.                     9:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
  1132.                    20:d=2  hl=2 l=   0 prim:   NULL
  1133.                    22:d=1  hl=4 l= 609 prim:  OCTET STRING */
  1134.  
  1135.                 if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
  1136.                     $this->_string_shift($key, 3);
  1137.                     $tag = CRYPT_RSA_ASN1_SEQUENCE;
  1138.                 }
  1139.  
  1140.                 if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  1141.                     /* intended for keys for which OpenSSL's asn1parse returns the following:
  1142.  
  1143.                         0:d=0  hl=4 l= 290 cons: SEQUENCE
  1144.                         4:d=1  hl=2 l=  13 cons:  SEQUENCE
  1145.                         6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
  1146.                        17:d=2  hl=2 l=   0 prim:   NULL
  1147.                        19:d=1  hl=4 l= 271 prim:  BIT STRING */
  1148.                     $this->_string_shift($key, $this->_decodeLength($key));
  1149.                     $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
  1150.                     $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
  1151.                     // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  1152.                     //  unused bits in the final subsequent octet. The number shall be in the range zero to seven."
  1153.                     //  -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  1154.                     if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
  1155.                         $this->_string_shift($key);
  1156.                     }
  1157.                     if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1158.                         throw $is_encrypted ?
  1159.                             new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1160.                             new FormatNotSupportedException('PKCS1: Expected a second SEQUENCE tag');
  1161.                     }
  1162.                     if ($this->_decodeLength($key) != strlen($key)) {
  1163.                         throw $is_encrypted ?
  1164.                             new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1165.                             new FormatNotSupportedException('PKCS1: Tag length and key length should match');
  1166.                     }
  1167.                     $tag = ord($this->_string_shift($key));
  1168.                 }
  1169.                 if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  1170.                     throw $is_encrypted ?
  1171.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1172.                         new FormatNotSupportedException('PKCS1: Expected an INTEGER tag');
  1173.                 }
  1174.  
  1175.                 $length = $this->_decodeLength($key);
  1176.                 $temp = $this->_string_shift($key, $length);
  1177.                 if (strlen($temp) != 1 || ord($temp) > 2) {
  1178.                     $components['modulus'] = new Math_BigInteger($temp, 256);
  1179.                     $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  1180.                     $length = $this->_decodeLength($key);
  1181.                     $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1182.  
  1183.                     return $components;
  1184.                 }
  1185.                 if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  1186.                     throw $is_encrypted ?
  1187.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1188.                         new FormatNotSupportedException('PKCS1: Expected a second INTEGER tag');
  1189.                 }
  1190.                 $length = $this->_decodeLength($key);
  1191.                 $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1192.                 $this->_string_shift($key);
  1193.                 $length = $this->_decodeLength($key);
  1194.                 $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1195.                 $this->_string_shift($key);
  1196.                 $length = $this->_decodeLength($key);
  1197.                 $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1198.                 $this->_string_shift($key);
  1199.                 $length = $this->_decodeLength($key);
  1200.                 $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1201.                 $this->_string_shift($key);
  1202.                 $length = $this->_decodeLength($key);
  1203.                 $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1204.                 $this->_string_shift($key);
  1205.                 $length = $this->_decodeLength($key);
  1206.                 $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1207.                 $this->_string_shift($key);
  1208.                 $length = $this->_decodeLength($key);
  1209.                 $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1210.                 $this->_string_shift($key);
  1211.                 $length = $this->_decodeLength($key);
  1212.                 $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1213.  
  1214.                 if (!empty($key)) {
  1215.                     if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1216.                         throw $is_encrypted ?
  1217.                             new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1218.                             new FormatNotSupportedException('PKCS1: Expected another SEQUENCE tag');
  1219.                     }
  1220.                     $this->_decodeLength($key);
  1221.                     while (!empty($key)) {
  1222.                         if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1223.                             throw $is_encrypted ?
  1224.                                 new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1225.                                 new FormatNotSupportedException('PKCS1: Expected yet another SEQUENCE tag');
  1226.                         }
  1227.                         $this->_decodeLength($key);
  1228.                         $key = substr($key, 1);
  1229.                         $length = $this->_decodeLength($key);
  1230.                         $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1231.                         $this->_string_shift($key);
  1232.                         $length = $this->_decodeLength($key);
  1233.                         $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1234.                         $this->_string_shift($key);
  1235.                         $length = $this->_decodeLength($key);
  1236.                         $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1237.                     }
  1238.                 }
  1239.  
  1240.                 return $components;
  1241.             case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  1242.                 $parts = explode(' ', $key, 3);
  1243.  
  1244.                 $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
  1245.                 if ($key === false) {
  1246.                     throw new FormatNotSupportedException('OpenSSH public: Public key not present or badly formated');
  1247.                 }
  1248.  
  1249.                 $comment = isset($parts[2]) ? $parts[2] : false;
  1250.  
  1251.                 $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  1252.  
  1253.                 if (strlen($key) <= 4) {
  1254.                     throw new FormatNotSupportedException('OpenSSH public: Key data too short');
  1255.                 }
  1256.                 extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1257.                 $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1258.                 if (strlen($key) <= 4) {
  1259.                     throw new FormatNotSupportedException('OpenSSH public: public exponent data too short');
  1260.                 }
  1261.                 extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1262.                 $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1263.  
  1264.                 if ($cleanup && strlen($key)) {
  1265.                     if (strlen($key) <= 4) {
  1266.                         throw new FormatNotSupportedException('OpenSSH public: data too short');
  1267.                     }
  1268.                     extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1269.                     $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1270.                     if (strlen($key)) {
  1271.                         throw new FormatNotSupportedException('OpenSSH public: Junk key data present');
  1272.                     }
  1273.                     return array(
  1274.                         'modulus' => $realModulus,
  1275.                         'publicExponent' => $modulus,
  1276.                         'comment' => $comment
  1277.                     );
  1278.                 } else {
  1279.                     if (strlen($key)) {
  1280.                         throw new FormatNotSupportedException('OpenSSH public: Extra key data present');
  1281.                     }
  1282.                     return array(
  1283.                         'modulus' => $modulus,
  1284.                         'publicExponent' => $publicExponent,
  1285.                         'comment' => $comment
  1286.                     );
  1287.                 }
  1288.             // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
  1289.             // http://en.wikipedia.org/wiki/XML_Signature
  1290.             case CRYPT_RSA_PRIVATE_FORMAT_XML:
  1291.             case CRYPT_RSA_PUBLIC_FORMAT_XML:
  1292.                 $this->components = array();
  1293.  
  1294.                 $xml = xml_parser_create('UTF-8');
  1295.                 xml_set_object($xml, $this);
  1296.                 xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
  1297.                 xml_set_character_data_handler($xml, '_data_handler');
  1298.                 // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
  1299.                 if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
  1300.                     throw new FormatNotSupportedException('XML: Unable to parse key');
  1301.                 }
  1302.  
  1303.                 return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
  1304.             // from PuTTY's SSHPUBK.C
  1305.             case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  1306.                 $components = array();
  1307.                 $key = preg_split('#\r\n|\r|\n#', $key);
  1308.                 $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
  1309.                 if ($type != 'ssh-rsa') {
  1310.                     throw new FormatNotSupportedException('PuTTY: Only ssh-rsa keys are supported');
  1311.                 }
  1312.                 $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
  1313.                 $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
  1314.  
  1315.                 $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
  1316.                 $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
  1317.                 $public = substr($public, 11);
  1318.                 extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1319.                 $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  1320.                 extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1321.                 $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  1322.  
  1323.                 $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
  1324.                 $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
  1325.  
  1326.                 switch ($encryption) {
  1327.                     case 'aes256-cbc':
  1328.                         if (!class_exists('Crypt_AES')) {
  1329.                             require_once('Crypt/AES.php');
  1330.                         }
  1331.                         $symkey = '';
  1332.                         $sequence = 0;
  1333.                         while (strlen($symkey) < 32) {
  1334.                             $temp = pack('Na*', $sequence++, $this->password);
  1335.                             $symkey.= pack('H*', sha1($temp));
  1336.                         }
  1337.                         $symkey = substr($symkey, 0, 32);
  1338.                         $crypto = new Crypt_AES();
  1339.                 }
  1340.  
  1341.                 $is_encrypted = $encryption != 'none';
  1342.                 if ($is_encrypted) {
  1343.                     $crypto->setKey($symkey);
  1344.                     $crypto->disablePadding();
  1345.                     try {
  1346.                         $private = $crypto->decrypt($private);
  1347.                     } catch (InvalidPaddingException $e) {
  1348.                         throw new BadPasswordException('Unable to decode key. Likely cause: bad password');
  1349.                     }
  1350.                 }
  1351.  
  1352.                 extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1353.                 if (strlen($private) < $length) {
  1354.                     throw $is_encrypted ?
  1355.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1356.                         new FormatNotSupportedException('PuTTY: length not long enough');
  1357.                 }
  1358.                 $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  1359.                 extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1360.                 if (strlen($private) < $length) {
  1361.                     throw $is_encrypted ?
  1362.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1363.                         new FormatNotSupportedException('PuTTY: length not long enough');
  1364.                 }
  1365.                 $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  1366.                 extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1367.                 if (strlen($private) < $length) {
  1368.                     throw $is_encrypted ?
  1369.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1370.                         new FormatNotSupportedException('PuTTY: length not long enough');
  1371.                 }
  1372.                 $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  1373.  
  1374.                 $temp = $components['primes'][1]->subtract($this->one);
  1375.                 $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
  1376.                 $temp = $components['primes'][2]->subtract($this->one);
  1377.                 $components['exponents'][] = $components['publicExponent']->modInverse($temp);
  1378.  
  1379.                 extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1380.                 if (strlen($private) < $length) {
  1381.                     throw $is_encrypted ?
  1382.                         new BadPasswordException('Unable to decode key. Likely cause: bad password') :
  1383.                         new FormatNotSupportedException('PuTTY: length not long enough');
  1384.                 }
  1385.                 $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  1386.  
  1387.                 return $components;
  1388.         }
  1389.     }
  1390.  
  1391.     /**
  1392.      * Returns the key size
  1393.      *
  1394.      * More specifically, this returns the size of the modulo in bits.
  1395.      *
  1396.      * @access public
  1397.      * @return Integer
  1398.      */
  1399.     function getSize()
  1400.     {
  1401.         return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
  1402.     }
  1403.  
  1404.     /**
  1405.      * Start Element Handler
  1406.      *
  1407.      * Called by xml_set_element_handler()
  1408.      *
  1409.      * @access private
  1410.      * @param Resource $parser
  1411.      * @param String $name
  1412.      * @param Array $attribs
  1413.      */
  1414.     function _start_element_handler($parser, $name, $attribs)
  1415.     {
  1416.         //$name = strtoupper($name);
  1417.         switch ($name) {
  1418.             case 'MODULUS':
  1419.                 $this->current = &$this->components['modulus'];
  1420.                 break;
  1421.             case 'EXPONENT':
  1422.                 $this->current = &$this->components['publicExponent'];
  1423.                 break;
  1424.             case 'P':
  1425.                 $this->current = &$this->components['primes'][1];
  1426.                 break;
  1427.             case 'Q':
  1428.                 $this->current = &$this->components['primes'][2];
  1429.                 break;
  1430.             case 'DP':
  1431.                 $this->current = &$this->components['exponents'][1];
  1432.                 break;
  1433.             case 'DQ':
  1434.                 $this->current = &$this->components['exponents'][2];
  1435.                 break;
  1436.             case 'INVERSEQ':
  1437.                 $this->current = &$this->components['coefficients'][2];
  1438.                 break;
  1439.             case 'D':
  1440.                 $this->current = &$this->components['privateExponent'];
  1441.         }
  1442.         $this->current = '';
  1443.     }
  1444.  
  1445.     /**
  1446.      * Stop Element Handler
  1447.      *
  1448.      * Called by xml_set_element_handler()
  1449.      *
  1450.      * @access private
  1451.      * @param Resource $parser
  1452.      * @param String $name
  1453.      */
  1454.     function _stop_element_handler($parser, $name)
  1455.     {
  1456.         //$name = strtoupper($name);
  1457.         if ($name == 'RSAKEYVALUE') {
  1458.             return;
  1459.         }
  1460.         $this->current = new Math_BigInteger(base64_decode($this->current), 256);
  1461.         unset($this->current);
  1462.     }
  1463.  
  1464.     /**
  1465.      * Data Handler
  1466.      *
  1467.      * Called by xml_set_character_data_handler()
  1468.      *
  1469.      * @access private
  1470.      * @param Resource $parser
  1471.      * @param String $data
  1472.      */
  1473.     function _data_handler($parser, $data)
  1474.     {
  1475.         if (!isset($this->current) || is_object($this->current)) {
  1476.             return;
  1477.         }
  1478.         $this->current.= trim($data);
  1479.     }
  1480.  
  1481.     /**
  1482.      * Loads a public or private key
  1483.      *
  1484.      * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  1485.      *
  1486.      * @access public
  1487.      * @param String $key
  1488.      * @param Integer $type optional
  1489.      */
  1490.     function loadKey($key, $type = false)
  1491.     {
  1492.         if ($type === false) {
  1493.             $types = array(
  1494.                 CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1495.                 CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
  1496.                 CRYPT_RSA_PRIVATE_FORMAT_XML,
  1497.                 CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
  1498.                 CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1499.             );
  1500.             foreach ($types as $type) {
  1501.                 try {
  1502.                     $components = $this->_parseKey($key, $type);
  1503.                     break;
  1504.                 } catch (FormatNotSupportedException $e) {
  1505.                 }
  1506.             }
  1507.             if (!isset($components)) {
  1508.                 throw new FormatNotSupportedException('Unable to find matching format');
  1509.             }
  1510.         } else {
  1511.             $components = $this->_parseKey($key, $type);
  1512.         }
  1513.  
  1514.         if (isset($components['comment']) && $components['comment'] !== false) {
  1515.             $this->comment = $components['comment'];
  1516.         }
  1517.         $this->modulus = $components['modulus'];
  1518.         $this->k = strlen($this->modulus->toBytes());
  1519.         $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  1520.         if (isset($components['primes'])) {
  1521.             $this->primes = $components['primes'];
  1522.             $this->exponents = $components['exponents'];
  1523.             $this->coefficients = $components['coefficients'];
  1524.             $this->publicExponent = $components['publicExponent'];
  1525.         } else {
  1526.             $this->primes = array();
  1527.             $this->exponents = array();
  1528.             $this->coefficients = array();
  1529.             $this->publicExponent = false;
  1530.         }
  1531.  
  1532.         return true;
  1533.     }
  1534.  
  1535.     /**
  1536.      * Sets the password
  1537.      *
  1538.      * Private keys can be encrypted with a password.  To unset the password, pass in the empty string or false.
  1539.      * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  1540.      *
  1541.      * @see createKey()
  1542.      * @see loadKey()
  1543.      * @access public
  1544.      * @param String $password
  1545.      */
  1546.     function setPassword($password = false)
  1547.     {
  1548.         $this->password = $password;
  1549.     }
  1550.  
  1551.     /**
  1552.      * Defines the public key
  1553.      *
  1554.      * Some private key formats define the public exponent and some don't.  Those that don't define it are problematic when
  1555.      * used in certain contexts.  For example, in SSH-2, RSA authentication works by sending the public key along with a
  1556.      * message signed by the private key to the server.  The SSH-2 server looks the public key up in an index of public keys
  1557.      * and if it's present then proceeds to verify the signature.  Problem is, if your private key doesn't include the public
  1558.      * exponent this won't work unless you manually add the public exponent.
  1559.      *
  1560.      * Do note that when a new key is loaded the index will be cleared.
  1561.      *
  1562.      * Returns true on success, false on failure
  1563.      *
  1564.      * @see getPublicKey()
  1565.      * @access public
  1566.      * @param String $key optional
  1567.      * @param Integer $type optional
  1568.      * @return Boolean
  1569.      */
  1570.     function setPublicKey($key = false, $type = false)
  1571.     {
  1572.         if ($key === false && !empty($this->modulus)) {
  1573.             $this->publicExponent = $this->exponent;
  1574.             return true;
  1575.         }
  1576.  
  1577.         if ($type === false) {
  1578.             $types = array(
  1579.                 CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1580.                 CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
  1581.                 CRYPT_RSA_PUBLIC_FORMAT_XML,
  1582.                 CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1583.             );
  1584.             foreach ($types as $type) {
  1585.                 try {
  1586.                     $components = $this->_parseKey($key, $type);
  1587.                     break;
  1588.                 } catch (FormatNotSupportedException $e) {
  1589.                 }
  1590.             }
  1591.             if (!isset($components)) {
  1592.                 throw new FormatNotSupportedException('Unable to find matching format');
  1593.             }
  1594.         } else {
  1595.             $components = $this->_parseKey($key, $type);
  1596.         }
  1597.  
  1598.         if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  1599.             $this->modulus = $components['modulus'];
  1600.             $this->exponent = $this->publicExponent = $components['publicExponent'];
  1601.             return true;
  1602.         }
  1603.  
  1604.         $this->publicExponent = $components['publicExponent'];
  1605.  
  1606.         return true;
  1607.     }
  1608.  
  1609.     /**
  1610.      * Returns the public key
  1611.      *
  1612.      * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  1613.      * or if the public key was set via setPublicKey().  If the currently loaded key is supposed to be the public key this
  1614.      * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  1615.      *
  1616.      * @see getPublicKey()
  1617.      * @access public
  1618.      * @param String $key
  1619.      * @param Integer $type optional
  1620.      */
  1621.     function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1622.     {
  1623.         if (empty($this->modulus) || empty($this->publicExponent)) {
  1624.             throw new KeyNotLoadedException('No public key has been loaded. Maybe you need to call setPublicKey()?');
  1625.         }
  1626.  
  1627.         $oldFormat = $this->publicKeyFormat;
  1628.         $this->publicKeyFormat = $type;
  1629.         $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  1630.         $this->publicKeyFormat = $oldFormat;
  1631.         return $temp;
  1632.     }
  1633.  
  1634.     /**
  1635.      * Returns the private key
  1636.      *
  1637.      * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  1638.      *
  1639.      * @see getPublicKey()
  1640.      * @access public
  1641.      * @param String $key
  1642.      * @param Integer $type optional
  1643.      */
  1644.     function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1645.     {
  1646.         if (empty($this->primes)) {
  1647.             throw new KeyNotLoadedException('No private key has been loaded.');
  1648.         }
  1649.  
  1650.         $oldFormat = $this->privateKeyFormat;
  1651.         $this->privateKeyFormat = $type;
  1652.         $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
  1653.         $this->privateKeyFormat = $oldFormat;
  1654.         return $temp;
  1655.     }
  1656.  
  1657.     /**
  1658.      * Returns a minimalistic private key
  1659.      *
  1660.      * Returns the private key without the prime number constituants.  Structurally identical to a public key that
  1661.      * hasn't been set as the public key
  1662.      *
  1663.      * @see getPrivateKey()
  1664.      * @access private
  1665.      * @param String $key
  1666.      * @param Integer $type optional
  1667.      */
  1668.     function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1669.     {
  1670.         if (empty($this->modulus) || empty($this->exponent)) {
  1671.             throw new KeyNotLoadedException('No private key has been loaded.');
  1672.         }
  1673.  
  1674.         $oldFormat = $this->publicKeyFormat;
  1675.         $this->publicKeyFormat = $mode;
  1676.         $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
  1677.         $this->publicKeyFormat = $oldFormat;
  1678.         return $temp;
  1679.     }
  1680.  
  1681.     /**
  1682.      *  __toString() magic method
  1683.      *
  1684.      * @access public
  1685.      */
  1686.     function __toString()
  1687.     {
  1688.         try {
  1689.             return $this->getPrivateKey($this->privateKeyFormat);
  1690.         } catch (KeyNotLoadedException $e) {
  1691.             return $this->_getPrivatePublicKey($this->publicKeyFormat);
  1692.         }
  1693.     }
  1694.  
  1695.     /**
  1696.      * Generates the smallest and largest numbers requiring $bits bits
  1697.      *
  1698.      * @access private
  1699.      * @param Integer $bits
  1700.      * @return Array
  1701.      */
  1702.     function _generateMinMax($bits)
  1703.     {
  1704.         $bytes = $bits >> 3;
  1705.         $min = str_repeat(chr(0), $bytes);
  1706.         $max = str_repeat(chr(0xFF), $bytes);
  1707.         $msb = $bits & 7;
  1708.         if ($msb) {
  1709.             $min = chr(1 << ($msb - 1)) . $min;
  1710.             $max = chr((1 << $msb) - 1) . $max;
  1711.         } else {
  1712.             $min[0] = chr(0x80);
  1713.         }
  1714.  
  1715.         return array(
  1716.             'min' => new Math_BigInteger($min, 256),
  1717.             'max' => new Math_BigInteger($max, 256)
  1718.         );
  1719.     }
  1720.  
  1721.     /**
  1722.      * DER-decode the length
  1723.      *
  1724.      * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4.  See
  1725.      * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1726.      *
  1727.      * @access private
  1728.      * @param String $string
  1729.      * @return Integer
  1730.      */
  1731.     function _decodeLength(&$string)
  1732.     {
  1733.         $length = ord($this->_string_shift($string));
  1734.         if ( $length & 0x80 ) { // definite length, long form
  1735.             $length&= 0x7F;
  1736.             $temp = $this->_string_shift($string, $length);
  1737.             list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1738.         }
  1739.         return $length;
  1740.     }
  1741.  
  1742.     /**
  1743.      * DER-encode the length
  1744.      *
  1745.      * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4.  See
  1746.      * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1747.      *
  1748.      * @access private
  1749.      * @param Integer $length
  1750.      * @return String
  1751.      */
  1752.     function _encodeLength($length)
  1753.     {
  1754.         if ($length <= 0x7F) {
  1755.             return chr($length);
  1756.         }
  1757.  
  1758.         $temp = ltrim(pack('N', $length), chr(0));
  1759.         return pack('Ca*', 0x80 | strlen($temp), $temp);
  1760.     }
  1761.  
  1762.     /**
  1763.      * String Shift
  1764.      *
  1765.      * Inspired by array_shift
  1766.      *
  1767.      * @param String $string
  1768.      * @param optional Integer $index
  1769.      * @return String
  1770.      * @access private
  1771.      */
  1772.     function _string_shift(&$string, $index = 1)
  1773.     {
  1774.         $substr = substr($string, 0, $index);
  1775.         $string = substr($string, $index);
  1776.         return $substr;
  1777.     }
  1778.  
  1779.     /**
  1780.      * Determines the private key format
  1781.      *
  1782.      * @see createKey()
  1783.      * @access public
  1784.      * @param Integer $format
  1785.      */
  1786.     function setPrivateKeyFormat($format)
  1787.     {
  1788.         $this->privateKeyFormat = $format;
  1789.     }
  1790.  
  1791.     /**
  1792.      * Determines the public key format
  1793.      *
  1794.      * @see createKey()
  1795.      * @access public
  1796.      * @param Integer $format
  1797.      */
  1798.     function setPublicKeyFormat($format)
  1799.     {
  1800.         $this->publicKeyFormat = $format;
  1801.     }
  1802.  
  1803.     /**
  1804.      * Determines which hashing function should be used
  1805.      *
  1806.      * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1807.      * decryption.  If $hash isn't supported, sha1 is used.
  1808.      *
  1809.      * @access public
  1810.      * @param String $hash
  1811.      */
  1812.     function setHash($hash)
  1813.     {
  1814.         // Crypt_Hash supports algorithms that PKCS#1 doesn't support.  md5-96 and sha1-96, for example.
  1815.         switch ($hash) {
  1816.             case 'md2':
  1817.             case 'md5':
  1818.             case 'sha1':
  1819.             case 'sha256':
  1820.             case 'sha384':
  1821.             case 'sha512':
  1822.                 $this->hash = new Crypt_Hash($hash);
  1823.                 $this->hashName = $hash;
  1824.                 break;
  1825.             default:
  1826.                 $this->hash = new Crypt_Hash('sha1');
  1827.                 $this->hashName = 'sha1';
  1828.         }
  1829.         $this->hLen = $this->hash->getLength();
  1830.     }
  1831.  
  1832.     /**
  1833.      * Determines which hashing function should be used for the mask generation function
  1834.      *
  1835.      * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1836.      * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1837.      *
  1838.      * @access public
  1839.      * @param String $hash
  1840.      */
  1841.     function setMGFHash($hash)
  1842.     {
  1843.         // Crypt_Hash supports algorithms that PKCS#1 doesn't support.  md5-96 and sha1-96, for example.
  1844.         switch ($hash) {
  1845.             case 'md2':
  1846.             case 'md5':
  1847.             case 'sha1':
  1848.             case 'sha256':
  1849.             case 'sha384':
  1850.             case 'sha512':
  1851.                 $this->mgfHash = new Crypt_Hash($hash);
  1852.                 break;
  1853.             default:
  1854.                 $this->mgfHash = new Crypt_Hash('sha1');
  1855.         }
  1856.         $this->mgfHLen = $this->mgfHash->getLength();
  1857.     }
  1858.  
  1859.     /**
  1860.      * Determines the salt length
  1861.      *
  1862.      * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1863.      *
  1864.      *    Typical salt lengths in octets are hLen (the length of the output
  1865.      *    of the hash function Hash) and 0.
  1866.      *
  1867.      * @access public
  1868.      * @param Integer $format
  1869.      */
  1870.     function setSaltLength($sLen)
  1871.     {
  1872.         $this->sLen = $sLen;
  1873.     }
  1874.  
  1875.     /**
  1876.      * Integer-to-Octet-String primitive
  1877.      *
  1878.      * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1879.      *
  1880.      * @access private
  1881.      * @param Math_BigInteger $x
  1882.      * @param Integer $xLen
  1883.      * @return String
  1884.      */
  1885.     function _i2osp($x, $xLen)
  1886.     {
  1887.         $x = $x->toBytes();
  1888.         if (strlen($x) > $xLen) {
  1889.             throw new EncodingException('Integer too large');
  1890.         }
  1891.         return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1892.     }
  1893.  
  1894.     /**
  1895.      * Octet-String-to-Integer primitive
  1896.      *
  1897.      * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1898.      *
  1899.      * @access private
  1900.      * @param String $x
  1901.      * @return Math_BigInteger
  1902.      */
  1903.     function _os2ip($x)
  1904.     {
  1905.         return new Math_BigInteger($x, 256);
  1906.     }
  1907.  
  1908.     /**
  1909.      * Exponentiate with or without Chinese Remainder Theorem
  1910.      *
  1911.      * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1912.      *
  1913.      * @access private
  1914.      * @param Math_BigInteger $x
  1915.      * @return Math_BigInteger
  1916.      */
  1917.     function _exponentiate($x)
  1918.     {
  1919.         if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1920.             return $x->modPow($this->exponent, $this->modulus);
  1921.         }
  1922.  
  1923.         $num_primes = count($this->primes);
  1924.  
  1925.         if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1926.             $m_i = array(
  1927.                 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1928.                 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1929.             );
  1930.             $h = $m_i[1]->subtract($m_i[2]);
  1931.             $h = $h->multiply($this->coefficients[2]);
  1932.             list(, $h) = $h->divide($this->primes[1]);
  1933.             $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1934.  
  1935.             $r = $this->primes[1];
  1936.             for ($i = 3; $i <= $num_primes; $i++) {
  1937.                 $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1938.  
  1939.                 $r = $r->multiply($this->primes[$i - 1]);
  1940.  
  1941.                 $h = $m_i->subtract($m);
  1942.                 $h = $h->multiply($this->coefficients[$i]);
  1943.                 list(, $h) = $h->divide($this->primes[$i]);
  1944.  
  1945.                 $m = $m->add($r->multiply($h));
  1946.             }
  1947.         } else {
  1948.             $smallest = $this->primes[1];
  1949.             for ($i = 2; $i <= $num_primes; $i++) {
  1950.                 if ($smallest->compare($this->primes[$i]) > 0) {
  1951.                     $smallest = $this->primes[$i];
  1952.                 }
  1953.             }
  1954.  
  1955.             $one = new Math_BigInteger(1);
  1956.  
  1957.             $r = $one->random($one, $smallest->subtract($one));
  1958.  
  1959.             $m_i = array(
  1960.                 1 => $this->_blind($x, $r, 1),
  1961.                 2 => $this->_blind($x, $r, 2)
  1962.             );
  1963.             $h = $m_i[1]->subtract($m_i[2]);
  1964.             $h = $h->multiply($this->coefficients[2]);
  1965.             list(, $h) = $h->divide($this->primes[1]);
  1966.             $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1967.  
  1968.             $r = $this->primes[1];
  1969.             for ($i = 3; $i <= $num_primes; $i++) {
  1970.                 $m_i = $this->_blind($x, $r, $i);
  1971.  
  1972.                 $r = $r->multiply($this->primes[$i - 1]);
  1973.  
  1974.                 $h = $m_i->subtract($m);
  1975.                 $h = $h->multiply($this->coefficients[$i]);
  1976.                 list(, $h) = $h->divide($this->primes[$i]);
  1977.  
  1978.                 $m = $m->add($r->multiply($h));
  1979.             }
  1980.         }
  1981.  
  1982.         return $m;
  1983.     }
  1984.  
  1985.     /**
  1986.      * Performs RSA Blinding
  1987.      *
  1988.      * Protects against timing attacks by employing RSA Blinding.
  1989.      * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1990.      *
  1991.      * @access private
  1992.      * @param Math_BigInteger $x
  1993.      * @param Math_BigInteger $r
  1994.      * @param Integer $i
  1995.      * @return Math_BigInteger
  1996.      */
  1997.     function _blind($x, $r, $i)
  1998.     {
  1999.         $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  2000.         $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  2001.  
  2002.         $r = $r->modInverse($this->primes[$i]);
  2003.         $x = $x->multiply($r);
  2004.         list(, $x) = $x->divide($this->primes[$i]);
  2005.  
  2006.         return $x;
  2007.     }
  2008.  
  2009.     /**
  2010.      * Performs blinded RSA equality testing
  2011.      *
  2012.      * Protects against a particular type of timing attack described.
  2013.      *
  2014.      * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
  2015.      *
  2016.      * Thanks for the heads up singpolyma!
  2017.      *
  2018.      * @access private
  2019.      * @param String $x
  2020.      * @param String $y
  2021.      * @return Boolean
  2022.      */
  2023.     function _equals($x, $y)
  2024.     {
  2025.         if (strlen($x) != strlen($y)) {
  2026.             return false;
  2027.         }
  2028.  
  2029.         $result = 0;
  2030.         for ($i = 0; $i < strlen($x); $i++) {
  2031.             $result |= ord($x[$i]) ^ ord($y[$i]);
  2032.         }
  2033.  
  2034.         return $result == 0;
  2035.     }
  2036.  
  2037.     /**
  2038.      * RSAEP
  2039.      *
  2040.      * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  2041.      *
  2042.      * @access private
  2043.      * @param Math_BigInteger $m
  2044.      * @return Math_BigInteger
  2045.      */
  2046.     function _rsaep($m)
  2047.     {
  2048.         if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  2049.             throw new EncryptionException('Message representative out of range');
  2050.         }
  2051.         return $this->_exponentiate($m);
  2052.     }
  2053.  
  2054.     /**
  2055.      * RSADP
  2056.      *
  2057.      * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  2058.      *
  2059.      * @access private
  2060.      * @param Math_BigInteger $c
  2061.      * @return Math_BigInteger
  2062.      */
  2063.     function _rsadp($c)
  2064.     {
  2065.         if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
  2066.             throw new DecryptionException('Ciphertext representative out of range');
  2067.         }
  2068.         return $this->_exponentiate($c);
  2069.     }
  2070.  
  2071.     /**
  2072.      * RSASP1
  2073.      *
  2074.      * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  2075.      *
  2076.      * @access private
  2077.      * @param Math_BigInteger $m
  2078.      * @return Math_BigInteger
  2079.      */
  2080.     function _rsasp1($m)
  2081.     {
  2082.         if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  2083.             throw new SigningException('Message representative out of range');
  2084.         }
  2085.         return $this->_exponentiate($m);
  2086.     }
  2087.  
  2088.     /**
  2089.      * RSAVP1
  2090.      *
  2091.      * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  2092.      *
  2093.      * @access private
  2094.      * @param Math_BigInteger $s
  2095.      * @return Math_BigInteger
  2096.      */
  2097.     function _rsavp1($s)
  2098.     {
  2099.         if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
  2100.             throw new VerificationException('Signature representative out of range');
  2101.             return false;
  2102.         }
  2103.         return $this->_exponentiate($s);
  2104.     }
  2105.  
  2106.     /**
  2107.      * MGF1
  2108.      *
  2109.      * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  2110.      *
  2111.      * @access private
  2112.      * @param String $mgfSeed
  2113.      * @param Integer $mgfLen
  2114.      * @return String
  2115.      */
  2116.     function _mgf1($mgfSeed, $maskLen)
  2117.     {
  2118.         // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  2119.  
  2120.         $t = '';
  2121.         $count = ceil($maskLen / $this->mgfHLen);
  2122.         for ($i = 0; $i < $count; $i++) {
  2123.             $c = pack('N', $i);
  2124.             $t.= $this->mgfHash->hash($mgfSeed . $c);
  2125.         }
  2126.  
  2127.         return substr($t, 0, $maskLen);
  2128.     }
  2129.  
  2130.     /**
  2131.      * RSAES-OAEP-ENCRYPT
  2132.      *
  2133.      * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  2134.      * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  2135.      *
  2136.      * @access private
  2137.      * @param String $m
  2138.      * @param String $l
  2139.      * @return String
  2140.      */
  2141.     function _rsaes_oaep_encrypt($m, $l = '')
  2142.     {
  2143.         $mLen = strlen($m);
  2144.  
  2145.         // Length checking
  2146.  
  2147.         // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2148.         // be output.
  2149.  
  2150.         if ($mLen > $this->k - 2 * $this->hLen - 2) {
  2151.             throw new EncryptionException('Message too long');
  2152.         }
  2153.  
  2154.         // EME-OAEP encoding
  2155.  
  2156.         $lHash = $this->hash->hash($l);
  2157.         $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  2158.         $db = $lHash . $ps . chr(1) . $m;
  2159.         $seed = crypt_random_string($this->hLen);
  2160.         $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2161.         $maskedDB = $db ^ $dbMask;
  2162.         $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2163.         $maskedSeed = $seed ^ $seedMask;
  2164.         $em = chr(0) . $maskedSeed . $maskedDB;
  2165.  
  2166.         // RSA encryption
  2167.  
  2168.         $m = $this->_os2ip($em);
  2169.         $c = $this->_rsaep($m);
  2170.         $c = $this->_i2osp($c, $this->k);
  2171.  
  2172.         // Output the ciphertext C
  2173.  
  2174.         return $c;
  2175.     }
  2176.  
  2177.     /**
  2178.      * RSAES-OAEP-DECRYPT
  2179.      *
  2180.      * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}.  The fact that the error
  2181.      * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  2182.      *
  2183.      *    Note.  Care must be taken to ensure that an opponent cannot
  2184.      *    distinguish the different error conditions in Step 3.g, whether by
  2185.      *    error message or timing, or, more generally, learn partial
  2186.      *    information about the encoded message EM.  Otherwise an opponent may
  2187.      *    be able to obtain useful information about the decryption of the
  2188.      *    ciphertext C, leading to a chosen-ciphertext attack such as the one
  2189.      *    observed by Manger [36].
  2190.      *
  2191.      * As for $l...  to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  2192.      *
  2193.      *    Both the encryption and the decryption operations of RSAES-OAEP take
  2194.      *    the value of a label L as input.  In this version of PKCS #1, L is
  2195.      *    the empty string; other uses of the label are outside the scope of
  2196.      *    this document.
  2197.      *
  2198.      * @access private
  2199.      * @param String $c
  2200.      * @param String $l
  2201.      * @return String
  2202.      */
  2203.     function _rsaes_oaep_decrypt($c, $l = '')
  2204.     {
  2205.         // Length checking
  2206.  
  2207.         // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2208.         // be output.
  2209.  
  2210.         if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  2211.             throw new DecryptionException('Decryption error');
  2212.         }
  2213.  
  2214.         // RSA decryption
  2215.  
  2216.         $c = $this->_os2ip($c);
  2217.         $m = $this->_rsadp($c);
  2218.         if ($m === false) {
  2219.             throw new DecryptionException('Decryption error');
  2220.         }
  2221.         $em = $this->_i2osp($m, $this->k);
  2222.  
  2223.         // EME-OAEP decoding
  2224.  
  2225.         $lHash = $this->hash->hash($l);
  2226.         $y = ord($em[0]);
  2227.         $maskedSeed = substr($em, 1, $this->hLen);
  2228.         $maskedDB = substr($em, $this->hLen + 1);
  2229.         $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2230.         $seed = $maskedSeed ^ $seedMask;
  2231.         $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2232.         $db = $maskedDB ^ $dbMask;
  2233.         $lHash2 = substr($db, 0, $this->hLen);
  2234.         $m = substr($db, $this->hLen);
  2235.         if ($lHash != $lHash2) {
  2236.             throw new DecryptionException('Decryption error');
  2237.         }
  2238.         $m = ltrim($m, chr(0));
  2239.         if (ord($m[0]) != 1) {
  2240.             throw new DecryptionException('Decryption error');
  2241.         }
  2242.  
  2243.         // Output the message M
  2244.  
  2245.         return substr($m, 1);
  2246.     }
  2247.  
  2248.     /**
  2249.      * RSAES-PKCS1-V1_5-ENCRYPT
  2250.      *
  2251.      * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  2252.      *
  2253.      * @access private
  2254.      * @param String $m
  2255.      * @return String
  2256.      */
  2257.     function _rsaes_pkcs1_v1_5_encrypt($m)
  2258.     {
  2259.         $mLen = strlen($m);
  2260.  
  2261.         // Length checking
  2262.  
  2263.         if ($mLen > $this->k - 11) {
  2264.             throw new EncryptionException('Message too long');
  2265.         }
  2266.  
  2267.         // EME-PKCS1-v1_5 encoding
  2268.  
  2269.         $psLen = $this->k - $mLen - 3;
  2270.         $ps = '';
  2271.         while (strlen($ps) != $psLen) {
  2272.             $temp = crypt_random_string($psLen - strlen($ps));
  2273.             $temp = str_replace("\x00", '', $temp);
  2274.             $ps.= $temp;
  2275.         }
  2276.         $type = 2;
  2277.         // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  2278.         if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
  2279.             $type = 1;
  2280.             // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  2281.             $ps = str_repeat("\xFF", $psLen);
  2282.         }
  2283.         $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  2284.  
  2285.         // RSA encryption
  2286.         $m = $this->_os2ip($em);
  2287.         $c = $this->_rsaep($m);
  2288.         $c = $this->_i2osp($c, $this->k);
  2289.  
  2290.         // Output the ciphertext C
  2291.  
  2292.         return $c;
  2293.     }
  2294.  
  2295.     /**
  2296.      * RSAES-PKCS1-V1_5-DECRYPT
  2297.      *
  2298.      * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  2299.      *
  2300.      * For compatability purposes, this function departs slightly from the description given in RFC3447.
  2301.      * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  2302.      * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  2303.      * public key should have the second byte set to 2.  In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  2304.      * to be 2 regardless of which key is used.  For compatability purposes, we'll just check to make sure the
  2305.      * second byte is 2 or less.  If it is, we'll accept the decrypted string as valid.
  2306.      *
  2307.      * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
  2308.      * with a strictly PKCS#1 v1.5 compliant RSA implementation.  Public key encrypted ciphertext's should but
  2309.      * not private key encrypted ciphertext's.
  2310.      *
  2311.      * @access private
  2312.      * @param String $c
  2313.      * @return String
  2314.      */
  2315.     function _rsaes_pkcs1_v1_5_decrypt($c)
  2316.     {
  2317.         // Length checking
  2318.  
  2319.         if (strlen($c) != $this->k) { // or if k < 11
  2320.             throw new DecryptionException('Decryption error');
  2321.         }
  2322.  
  2323.         // RSA decryption
  2324.  
  2325.         $c = $this->_os2ip($c);
  2326.         $m = $this->_rsadp($c);
  2327.  
  2328.         if ($m === false) {
  2329.             throw new DecryptionException('Decryption error');
  2330.         }
  2331.         $em = $this->_i2osp($m, $this->k);
  2332.  
  2333.         // EME-PKCS1-v1_5 decoding
  2334.  
  2335.         if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  2336.             throw new DecryptionException('Decryption error');
  2337.         }
  2338.  
  2339.         $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  2340.         $m = substr($em, strlen($ps) + 3);
  2341.  
  2342.         if (strlen($ps) < 8) {
  2343.             throw new DecryptionException('Decryption error');
  2344.         }
  2345.  
  2346.         // Output M
  2347.  
  2348.         return $m;
  2349.     }
  2350.  
  2351.     /**
  2352.      * EMSA-PSS-ENCODE
  2353.      *
  2354.      * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  2355.      *
  2356.      * @access private
  2357.      * @param String $m
  2358.      * @param Integer $emBits
  2359.      */
  2360.     function _emsa_pss_encode($m, $emBits)
  2361.     {
  2362.         // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2363.         // be output.
  2364.  
  2365.         $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  2366.         $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  2367.  
  2368.         $mHash = $this->hash->hash($m);
  2369.         if ($emLen < $this->hLen + $sLen + 2) {
  2370.             throw new SigningException('Encoding error');
  2371.         }
  2372.  
  2373.         $salt = crypt_random_string($sLen);
  2374.         $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2375.         $h = $this->hash->hash($m2);
  2376.         $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  2377.         $db = $ps . chr(1) . $salt;
  2378.         $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2379.         $maskedDB = $db ^ $dbMask;
  2380.         $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  2381.         $em = $maskedDB . $h . chr(0xBC);
  2382.  
  2383.         return $em;
  2384.     }
  2385.  
  2386.     /**
  2387.      * EMSA-PSS-VERIFY
  2388.      *
  2389.      * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  2390.      *
  2391.      * @access private
  2392.      * @param String $m
  2393.      * @param String $em
  2394.      * @param Integer $emBits
  2395.      * @return String
  2396.      */
  2397.     function _emsa_pss_verify($m, $em, $emBits)
  2398.     {
  2399.         // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2400.         // be output.
  2401.  
  2402.         $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  2403.         $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  2404.  
  2405.         $mHash = $this->hash->hash($m);
  2406.         if ($emLen < $this->hLen + $sLen + 2) {
  2407.             return false;
  2408.         }
  2409.  
  2410.         if ($em[strlen($em) - 1] != chr(0xBC)) {
  2411.             return false;
  2412.         }
  2413.  
  2414.         $maskedDB = substr($em, 0, -$this->hLen - 1);
  2415.         $h = substr($em, -$this->hLen - 1, $this->hLen);
  2416.         $temp = chr(0xFF << ($emBits & 7));
  2417.         if ((~$maskedDB[0] & $temp) != $temp) {
  2418.             return false;
  2419.         }
  2420.         $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2421.         $db = $maskedDB ^ $dbMask;
  2422.         $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  2423.         $temp = $emLen - $this->hLen - $sLen - 2;
  2424.         if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  2425.             return false;
  2426.         }
  2427.         $salt = substr($db, $temp + 1); // should be $sLen long
  2428.         $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2429.         $h2 = $this->hash->hash($m2);
  2430.         return $this->_equals($h, $h2);
  2431.     }
  2432.  
  2433.     /**
  2434.      * RSASSA-PSS-SIGN
  2435.      *
  2436.      * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  2437.      *
  2438.      * @access private
  2439.      * @param String $m
  2440.      * @return String
  2441.      */
  2442.     function _rsassa_pss_sign($m)
  2443.     {
  2444.         // EMSA-PSS encoding
  2445.  
  2446.         $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  2447.  
  2448.         // RSA signature
  2449.  
  2450.         $m = $this->_os2ip($em);
  2451.         $s = $this->_rsasp1($m);
  2452.         $s = $this->_i2osp($s, $this->k);
  2453.  
  2454.         // Output the signature S
  2455.  
  2456.         return $s;
  2457.     }
  2458.  
  2459.     /**
  2460.      * RSASSA-PSS-VERIFY
  2461.      *
  2462.      * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  2463.      *
  2464.      * @access private
  2465.      * @param String $m
  2466.      * @param String $s
  2467.      * @return String
  2468.      */
  2469.     function _rsassa_pss_verify($m, $s)
  2470.     {
  2471.         // Length checking
  2472.  
  2473.         if (strlen($s) != $this->k) {
  2474.             throw new VerificationException('Invalid signature');
  2475.         }
  2476.  
  2477.         // RSA verification
  2478.  
  2479.         $modBits = 8 * $this->k;
  2480.  
  2481.         $s2 = $this->_os2ip($s);
  2482.         $m2 = $this->_rsavp1($s2);
  2483.         if ($m2 === false) {
  2484.             throw new VerificationException('Invalid signature');
  2485.         }
  2486.         $em = $this->_i2osp($m2, $modBits >> 3);
  2487.         if ($em === false) {
  2488.             throw new VerificationException('Invalid signature');
  2489.         }
  2490.  
  2491.         // EMSA-PSS verification
  2492.  
  2493.         return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  2494.     }
  2495.  
  2496.     /**
  2497.      * EMSA-PKCS1-V1_5-ENCODE
  2498.      *
  2499.      * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  2500.      *
  2501.      * @access private
  2502.      * @param String $m
  2503.      * @param Integer $emLen
  2504.      * @return String
  2505.      */
  2506.     function _emsa_pkcs1_v1_5_encode($m, $emLen)
  2507.     {
  2508.         $h = $this->hash->hash($m);
  2509.         if ($h === false) {
  2510.             return false;
  2511.         }
  2512.  
  2513.         // see http://tools.ietf.org/html/rfc3447#page-43
  2514.         switch ($this->hashName) {
  2515.             case 'md2':
  2516.                 $t = pack('H*', '3020300c06082a864886f70d020205000410');
  2517.                 break;
  2518.             case 'md5':
  2519.                 $t = pack('H*', '3020300c06082a864886f70d020505000410');
  2520.                 break;
  2521.             case 'sha1':
  2522.                 $t = pack('H*', '3021300906052b0e03021a05000414');
  2523.                 break;
  2524.             case 'sha256':
  2525.                 $t = pack('H*', '3031300d060960864801650304020105000420');
  2526.                 break;
  2527.             case 'sha384':
  2528.                 $t = pack('H*', '3041300d060960864801650304020205000430');
  2529.                 break;
  2530.             case 'sha512':
  2531.                 $t = pack('H*', '3051300d060960864801650304020305000440');
  2532.         }
  2533.         $t.= $h;
  2534.         $tLen = strlen($t);
  2535.  
  2536.         if ($emLen < $tLen + 11) {
  2537.             throw new EncodingException('Intended encoded message length too short');
  2538.         }
  2539.  
  2540.         $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  2541.  
  2542.         $em = "\0\1$ps\0$t";
  2543.  
  2544.         return $em;
  2545.     }
  2546.  
  2547.     /**
  2548.      * RSASSA-PKCS1-V1_5-SIGN
  2549.      *
  2550.      * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  2551.      *
  2552.      * @access private
  2553.      * @param String $m
  2554.      * @return String
  2555.      */
  2556.     function _rsassa_pkcs1_v1_5_sign($m)
  2557.     {
  2558.         // EMSA-PKCS1-v1_5 encoding
  2559.  
  2560.         $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2561.         if ($em === false) {
  2562.             throw new SigningException('RSA modulus too short');
  2563.         }
  2564.  
  2565.         // RSA signature
  2566.  
  2567.         $m = $this->_os2ip($em);
  2568.         $s = $this->_rsasp1($m);
  2569.         $s = $this->_i2osp($s, $this->k);
  2570.  
  2571.         // Output the signature S
  2572.  
  2573.         return $s;
  2574.     }
  2575.  
  2576.     /**
  2577.      * RSASSA-PKCS1-V1_5-VERIFY
  2578.      *
  2579.      * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  2580.      *
  2581.      * @access private
  2582.      * @param String $m
  2583.      * @return String
  2584.      */
  2585.     function _rsassa_pkcs1_v1_5_verify($m, $s)
  2586.     {
  2587.         // Length checking
  2588.  
  2589.         if (strlen($s) != $this->k) {
  2590.             throw new VerificationException('Invalid signature');
  2591.             return false;
  2592.         }
  2593.  
  2594.         // RSA verification
  2595.  
  2596.         $s = $this->_os2ip($s);
  2597.         $m2 = $this->_rsavp1($s);
  2598.         if ($m2 === false) {
  2599.             throw new VerificationException('Invalid signature');
  2600.         }
  2601.         $em = $this->_i2osp($m2, $this->k);
  2602.         if ($em === false) {
  2603.             throw new VerificationException('Invalid signature');
  2604.         }
  2605.  
  2606.         // EMSA-PKCS1-v1_5 encoding
  2607.  
  2608.         $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2609.         if ($em2 === false) {
  2610.             throw new VerificationException('RSA modulus too short');
  2611.             return false;
  2612.         }
  2613.  
  2614.         // Compare
  2615.         return $this->_equals($em, $em2);
  2616.     }
  2617.  
  2618.     /**
  2619.      * Set Encryption Mode
  2620.      *
  2621.      * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
  2622.      *
  2623.      * @access public
  2624.      * @param Integer $mode
  2625.      */
  2626.     function setEncryptionMode($mode)
  2627.     {
  2628.         $this->encryptionMode = $mode;
  2629.     }
  2630.  
  2631.     /**
  2632.      * Set Signature Mode
  2633.      *
  2634.      * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
  2635.      *
  2636.      * @access public
  2637.      * @param Integer $mode
  2638.      */
  2639.     function setSignatureMode($mode)
  2640.     {
  2641.         $this->signatureMode = $mode;
  2642.     }
  2643.  
  2644.     /**
  2645.      * Set public key comment.
  2646.      *
  2647.      * @access public
  2648.      * @param String $comment
  2649.      */
  2650.     function setComment($comment)
  2651.     {
  2652.         $this->comment = $comment;
  2653.     }
  2654.  
  2655.     /**
  2656.      * Get public key comment.
  2657.      *
  2658.      * @access public
  2659.      * @return String
  2660.      */
  2661.     function getComment()
  2662.     {
  2663.         return $this->comment;
  2664.     }
  2665.  
  2666.     /**
  2667.      * Encryption
  2668.      *
  2669.      * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
  2670.      * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  2671.      * be concatenated together.
  2672.      *
  2673.      * @see decrypt()
  2674.      * @access public
  2675.      * @param String $plaintext
  2676.      * @return String
  2677.      */
  2678.     function encrypt($plaintext)
  2679.     {
  2680.         switch ($this->encryptionMode) {
  2681.             case CRYPT_RSA_ENCRYPTION_PKCS1:
  2682.                 $length = $this->k - 11;
  2683.                 if ($length <= 0) {
  2684.                     return false;
  2685.                 }
  2686.  
  2687.                 $plaintext = str_split($plaintext, $length);
  2688.                 $ciphertext = '';
  2689.                 foreach ($plaintext as $m) {
  2690.                     $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
  2691.                 }
  2692.                 return $ciphertext;
  2693.             //case CRYPT_RSA_ENCRYPTION_OAEP:
  2694.             default:
  2695.                 $length = $this->k - 2 * $this->hLen - 2;
  2696.                 if ($length <= 0) {
  2697.                     return false;
  2698.                 }
  2699.  
  2700.                 $plaintext = str_split($plaintext, $length);
  2701.                 $ciphertext = '';
  2702.                 foreach ($plaintext as $m) {
  2703.                     $ciphertext.= $this->_rsaes_oaep_encrypt($m);
  2704.                 }
  2705.                 return $ciphertext;
  2706.         }
  2707.     }
  2708.  
  2709.     /**
  2710.      * Decryption
  2711.      *
  2712.      * @see encrypt()
  2713.      * @access public
  2714.      * @param String $plaintext
  2715.      * @return String
  2716.      */
  2717.     function decrypt($ciphertext)
  2718.     {
  2719.         if ($this->k <= 0) {
  2720.             return false;
  2721.         }
  2722.  
  2723.         $ciphertext = str_split($ciphertext, $this->k);
  2724.         $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
  2725.  
  2726.         $plaintext = '';
  2727.  
  2728.         switch ($this->encryptionMode) {
  2729.             case CRYPT_RSA_ENCRYPTION_PKCS1:
  2730.                 $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
  2731.                 break;
  2732.             //case CRYPT_RSA_ENCRYPTION_OAEP:
  2733.             default:
  2734.                 $decrypt = '_rsaes_oaep_decrypt';
  2735.         }
  2736.  
  2737.         foreach ($ciphertext as $c) {
  2738.             $temp = $this->$decrypt($c);
  2739.             if ($temp === false) {
  2740.                 return false;
  2741.             }
  2742.             $plaintext.= $temp;
  2743.         }
  2744.  
  2745.         return $plaintext;
  2746.     }
  2747.  
  2748.     /**
  2749.      * Create a signature
  2750.      *
  2751.      * @see verify()
  2752.      * @access public
  2753.      * @param String $message
  2754.      * @return String
  2755.      */
  2756.     function sign($message)
  2757.     {
  2758.         if (empty($this->modulus) || empty($this->exponent)) {
  2759.             return false;
  2760.         }
  2761.  
  2762.         switch ($this->signatureMode) {
  2763.             case CRYPT_RSA_SIGNATURE_PKCS1:
  2764.                 return $this->_rsassa_pkcs1_v1_5_sign($message);
  2765.             //case CRYPT_RSA_SIGNATURE_PSS:
  2766.             default:
  2767.                 return $this->_rsassa_pss_sign($message);
  2768.         }
  2769.     }
  2770.  
  2771.     /**
  2772.      * Verifies a signature
  2773.      *
  2774.      * @see sign()
  2775.      * @access public
  2776.      * @param String $message
  2777.      * @param String $signature
  2778.      * @return Boolean
  2779.      */
  2780.     function verify($message, $signature)
  2781.     {
  2782.         if (empty($this->modulus) || empty($this->exponent)) {
  2783.             return false;
  2784.         }
  2785.  
  2786.         switch ($this->signatureMode) {
  2787.             case CRYPT_RSA_SIGNATURE_PKCS1:
  2788.                 return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  2789.             //case CRYPT_RSA_SIGNATURE_PSS:
  2790.             default:
  2791.                 return $this->_rsassa_pss_verify($message, $signature);
  2792.         }
  2793.     }
  2794. }
Add Comment
Please, Sign In to add comment