PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/vendor/phpseclib/Crypt/RSA.php

https://bitbucket.org/arkross/venus
PHP | 2121 lines | 1021 code | 222 blank | 878 comment | 163 complexity | 3b78e8a927b49547c2bcee66dc52c6d1 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. namespace PHPSecLib;
  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: This library is free software; you can redistribute it and/or
  46. * modify it under the terms of the GNU Lesser General Public
  47. * License as published by the Free Software Foundation; either
  48. * version 2.1 of the License, or (at your option) any later version.
  49. *
  50. * This library is distributed in the hope that it will be useful,
  51. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  52. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  53. * Lesser General Public License for more details.
  54. *
  55. * You should have received a copy of the GNU Lesser General Public
  56. * License along with this library; if not, write to the Free Software
  57. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  58. * MA 02111-1307 USA
  59. *
  60. * @category Crypt
  61. * @package Crypt_RSA
  62. * @author Jim Wigginton <terrafrost@php.net>
  63. * @copyright MMIX Jim Wigginton
  64. * @license http://www.gnu.org/licenses/lgpl.txt
  65. * @version $Id: RSA.php,v 1.15 2010/04/10 15:57:02 terrafrost Exp $
  66. * @link http://phpseclib.sourceforge.net
  67. */
  68. /**
  69. * Include Math_BigInteger
  70. */
  71. require_once('Math/BigInteger.php');
  72. /**
  73. * Include Crypt_Random
  74. */
  75. require_once('Crypt/Random.php');
  76. /**
  77. * Include Crypt_Hash
  78. */
  79. require_once('Crypt/Hash.php');
  80. /**#@+
  81. * @access public
  82. * @see Crypt_RSA::encrypt()
  83. * @see Crypt_RSA::decrypt()
  84. */
  85. /**
  86. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  87. * (OAEP) for encryption / decryption.
  88. *
  89. * Uses sha1 by default.
  90. *
  91. * @see Crypt_RSA::setHash()
  92. * @see Crypt_RSA::setMGFHash()
  93. */
  94. define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
  95. /**
  96. * Use PKCS#1 padding.
  97. *
  98. * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  99. * compatability with protocols (like SSH-1) written before OAEP's introduction.
  100. */
  101. define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
  102. /**#@-*/
  103. /**#@+
  104. * @access public
  105. * @see Crypt_RSA::sign()
  106. * @see Crypt_RSA::verify()
  107. * @see Crypt_RSA::setHash()
  108. */
  109. /**
  110. * Use the Probabilistic Signature Scheme for signing
  111. *
  112. * Uses sha1 by default.
  113. *
  114. * @see Crypt_RSA::setSaltLength()
  115. * @see Crypt_RSA::setMGFHash()
  116. */
  117. define('CRYPT_RSA_SIGNATURE_PSS', 1);
  118. /**
  119. * Use the PKCS#1 scheme by default.
  120. *
  121. * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  122. * compatability with protocols (like SSH-2) written before PSS's introduction.
  123. */
  124. define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
  125. /**#@-*/
  126. /**#@+
  127. * @access private
  128. * @see Crypt_RSA::createKey()
  129. */
  130. /**
  131. * ASN1 Integer
  132. */
  133. define('CRYPT_RSA_ASN1_INTEGER', 2);
  134. /**
  135. * ASN1 Sequence (with the constucted bit set)
  136. */
  137. define('CRYPT_RSA_ASN1_SEQUENCE', 48);
  138. /**#@-*/
  139. /**#@+
  140. * @access private
  141. * @see Crypt_RSA::Crypt_RSA()
  142. */
  143. /**
  144. * To use the pure-PHP implementation
  145. */
  146. define('CRYPT_RSA_MODE_INTERNAL', 1);
  147. /**
  148. * To use the OpenSSL library
  149. *
  150. * (if enabled; otherwise, the internal implementation will be used)
  151. */
  152. define('CRYPT_RSA_MODE_OPENSSL', 2);
  153. /**#@-*/
  154. /**#@+
  155. * @access public
  156. * @see Crypt_RSA::createKey()
  157. * @see Crypt_RSA::setPrivateKeyFormat()
  158. */
  159. /**
  160. * PKCS#1 formatted private key
  161. *
  162. * Used by OpenSSH
  163. */
  164. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
  165. /**#@-*/
  166. /**#@+
  167. * @access public
  168. * @see Crypt_RSA::createKey()
  169. * @see Crypt_RSA::setPublicKeyFormat()
  170. */
  171. /**
  172. * Raw public key
  173. *
  174. * An array containing two Math_BigInteger objects.
  175. *
  176. * The exponent can be indexed with any of the following:
  177. *
  178. * 0, e, exponent, publicExponent
  179. *
  180. * The modulus can be indexed with any of the following:
  181. *
  182. * 1, n, modulo, modulus
  183. */
  184. define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 1);
  185. /**
  186. * PKCS#1 formatted public key
  187. */
  188. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 2);
  189. /**
  190. * OpenSSH formatted public key
  191. *
  192. * Place in $HOME/.ssh/authorized_keys
  193. */
  194. define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 3);
  195. /**#@-*/
  196. /**
  197. * Pure-PHP PKCS#1 compliant implementation of RSA.
  198. *
  199. * @author Jim Wigginton <terrafrost@php.net>
  200. * @version 0.1.0
  201. * @access public
  202. * @package Crypt_RSA
  203. */
  204. class Crypt_RSA {
  205. /**
  206. * Precomputed Zero
  207. *
  208. * @var Array
  209. * @access private
  210. */
  211. var $zero;
  212. /**
  213. * Precomputed One
  214. *
  215. * @var Array
  216. * @access private
  217. */
  218. var $one;
  219. /**
  220. * Private Key Format
  221. *
  222. * @var Integer
  223. * @access private
  224. */
  225. var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  226. /**
  227. * Public Key Format
  228. *
  229. * @var Integer
  230. * @access public
  231. */
  232. var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
  233. /**
  234. * Modulus (ie. n)
  235. *
  236. * @var Math_BigInteger
  237. * @access private
  238. */
  239. var $modulus;
  240. /**
  241. * Modulus length
  242. *
  243. * @var Math_BigInteger
  244. * @access private
  245. */
  246. var $k;
  247. /**
  248. * Exponent (ie. e or d)
  249. *
  250. * @var Math_BigInteger
  251. * @access private
  252. */
  253. var $exponent;
  254. /**
  255. * Primes for Chinese Remainder Theorem (ie. p and q)
  256. *
  257. * @var Array
  258. * @access private
  259. */
  260. var $primes;
  261. /**
  262. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  263. *
  264. * @var Array
  265. * @access private
  266. */
  267. var $exponents;
  268. /**
  269. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  270. *
  271. * @var Array
  272. * @access private
  273. */
  274. var $coefficients;
  275. /**
  276. * Hash name
  277. *
  278. * @var String
  279. * @access private
  280. */
  281. var $hashName;
  282. /**
  283. * Hash function
  284. *
  285. * @var Crypt_Hash
  286. * @access private
  287. */
  288. var $hash;
  289. /**
  290. * Length of hash function output
  291. *
  292. * @var Integer
  293. * @access private
  294. */
  295. var $hLen;
  296. /**
  297. * Length of salt
  298. *
  299. * @var Integer
  300. * @access private
  301. */
  302. var $sLen;
  303. /**
  304. * Hash function for the Mask Generation Function
  305. *
  306. * @var Crypt_Hash
  307. * @access private
  308. */
  309. var $mgfHash;
  310. /**
  311. * Length of MGF hash function output
  312. *
  313. * @var Integer
  314. * @access private
  315. */
  316. var $mgfHLen;
  317. /**
  318. * Encryption mode
  319. *
  320. * @var Integer
  321. * @access private
  322. */
  323. var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  324. /**
  325. * Signature mode
  326. *
  327. * @var Integer
  328. * @access private
  329. */
  330. var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  331. /**
  332. * Public Exponent
  333. *
  334. * @var Mixed
  335. * @access private
  336. */
  337. var $publicExponent = false;
  338. /**
  339. * Password
  340. *
  341. * @var String
  342. * @access private
  343. */
  344. var $password = '';
  345. /**
  346. * The constructor
  347. *
  348. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  349. * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  350. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  351. *
  352. * @return Crypt_RSA
  353. * @access public
  354. */
  355. function __construct()
  356. {
  357. if ( !defined('CRYPT_RSA_MODE') ) {
  358. switch (true) {
  359. //case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):
  360. // define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  361. // break;
  362. default:
  363. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  364. }
  365. }
  366. $this->zero = new Math_BigInteger();
  367. $this->one = new Math_BigInteger(1);
  368. $this->hash = new Crypt_Hash('sha1');
  369. $this->hLen = $this->hash->getLength();
  370. $this->hashName = 'sha1';
  371. $this->mgfHash = new Crypt_Hash('sha1');
  372. $this->mgfHLen = $this->mgfHash->getLength();
  373. }
  374. /**
  375. * Create public / private key pair
  376. *
  377. * Returns an array with the following three elements:
  378. * - 'privatekey': The private key.
  379. * - 'publickey': The public key.
  380. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  381. * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  382. *
  383. * @access public
  384. * @param optional Integer $bits
  385. * @param optional Integer $timeout
  386. * @param optional Math_BigInteger $p
  387. */
  388. function createKey($bits = 1024, $timeout = false, $partial = array())
  389. {
  390. if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL ) {
  391. $rsa = openssl_pkey_new(array('private_key_bits' => $bits));
  392. openssl_pkey_export($rsa, $privatekey);
  393. $publickey = openssl_pkey_get_details($rsa);
  394. $publickey = $publickey['key'];
  395. if ($this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_PKCS1) {
  396. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  397. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  398. }
  399. return array(
  400. 'privatekey' => $privatekey,
  401. 'publickey' => $publickey,
  402. 'partialkey' => false
  403. );
  404. }
  405. static $e;
  406. if (!isset($e)) {
  407. if (!defined('CRYPT_RSA_EXPONENT')) {
  408. // http://en.wikipedia.org/wiki/65537_%28number%29
  409. define('CRYPT_RSA_EXPONENT', '65537');
  410. }
  411. if (!defined('CRYPT_RSA_COMMENT')) {
  412. define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');
  413. }
  414. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  415. // than 256 bits.
  416. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  417. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  418. }
  419. $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
  420. }
  421. extract($this->_generateMinMax($bits));
  422. $absoluteMin = $min;
  423. $temp = $bits >> 1;
  424. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  425. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  426. $temp = CRYPT_RSA_SMALLEST_PRIME;
  427. } else {
  428. $num_primes = 2;
  429. }
  430. extract($this->_generateMinMax($temp + $bits % $temp));
  431. $finalMax = $max;
  432. extract($this->_generateMinMax($temp));
  433. $generator = new Math_BigInteger();
  434. $generator->setRandomGenerator('crypt_random');
  435. $n = $this->one->copy();
  436. if (!empty($partial)) {
  437. extract(unserialize($partial));
  438. } else {
  439. $exponents = $coefficients = $primes = array();
  440. $lcm = array(
  441. 'top' => $this->one->copy(),
  442. 'bottom' => false
  443. );
  444. }
  445. $start = time();
  446. $i0 = count($primes) + 1;
  447. do {
  448. for ($i = $i0; $i <= $num_primes; $i++) {
  449. if ($timeout !== false) {
  450. $timeout-= time() - $start;
  451. $start = time();
  452. if ($timeout <= 0) {
  453. return serialize(array(
  454. 'privatekey' => '',
  455. 'publickey' => '',
  456. 'partialkey' => array(
  457. 'primes' => $primes,
  458. 'coefficients' => $coefficients,
  459. 'lcm' => $lcm,
  460. 'exponents' => $exponents
  461. )
  462. ));
  463. }
  464. }
  465. if ($i == $num_primes) {
  466. list($min, $temp) = $absoluteMin->divide($n);
  467. if (!$temp->equals($this->zero)) {
  468. $min = $min->add($this->one); // ie. ceil()
  469. }
  470. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  471. } else {
  472. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  473. }
  474. if ($primes[$i] === false) { // if we've reached the timeout
  475. return array(
  476. 'privatekey' => '',
  477. 'publickey' => '',
  478. 'partialkey' => empty($primes) ? '' : serialize(array(
  479. 'primes' => array_slice($primes, 0, $i - 1),
  480. 'coefficients' => $coefficients,
  481. 'lcm' => $lcm,
  482. 'exponents' => $exponents
  483. ))
  484. );
  485. }
  486. // the first coefficient is calculated differently from the rest
  487. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  488. if ($i > 2) {
  489. $coefficients[$i] = $n->modInverse($primes[$i]);
  490. }
  491. $n = $n->multiply($primes[$i]);
  492. $temp = $primes[$i]->subtract($this->one);
  493. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  494. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  495. $lcm['top'] = $lcm['top']->multiply($temp);
  496. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  497. $exponents[$i] = $e->modInverse($temp);
  498. }
  499. list($lcm) = $lcm['top']->divide($lcm['bottom']);
  500. $gcd = $lcm->gcd($e);
  501. $i0 = 1;
  502. } while (!$gcd->equals($this->one));
  503. $d = $e->modInverse($lcm);
  504. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  505. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  506. // RSAPrivateKey ::= SEQUENCE {
  507. // version Version,
  508. // modulus INTEGER, -- n
  509. // publicExponent INTEGER, -- e
  510. // privateExponent INTEGER, -- d
  511. // prime1 INTEGER, -- p
  512. // prime2 INTEGER, -- q
  513. // exponent1 INTEGER, -- d mod (p-1)
  514. // exponent2 INTEGER, -- d mod (q-1)
  515. // coefficient INTEGER, -- (inverse of q) mod p
  516. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  517. // }
  518. return array(
  519. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  520. 'publickey' => $this->_convertPublicKey($n, $e),
  521. 'partialkey' => false
  522. );
  523. }
  524. /**
  525. * Convert a private key to the appropriate format.
  526. *
  527. * @access private
  528. * @see setPrivateKeyFormat()
  529. * @param String $RSAPrivateKey
  530. * @return String
  531. */
  532. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  533. {
  534. $num_primes = count($primes);
  535. $raw = array(
  536. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  537. 'modulus' => $n->toBytes(true),
  538. 'publicExponent' => $e->toBytes(true),
  539. 'privateExponent' => $d->toBytes(true),
  540. 'prime1' => $primes[1]->toBytes(true),
  541. 'prime2' => $primes[2]->toBytes(true),
  542. 'exponent1' => $exponents[1]->toBytes(true),
  543. 'exponent2' => $exponents[2]->toBytes(true),
  544. 'coefficient' => $coefficients[2]->toBytes(true)
  545. );
  546. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  547. // call _convertPublicKey() instead.
  548. switch ($this->privateKeyFormat) {
  549. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  550. $components = array();
  551. foreach ($raw as $name => $value) {
  552. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  553. }
  554. $RSAPrivateKey = implode('', $components);
  555. if ($num_primes > 2) {
  556. $OtherPrimeInfos = '';
  557. for ($i = 3; $i <= $num_primes; $i++) {
  558. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  559. //
  560. // OtherPrimeInfo ::= SEQUENCE {
  561. // prime INTEGER, -- ri
  562. // exponent INTEGER, -- di
  563. // coefficient INTEGER -- ti
  564. // }
  565. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  566. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  567. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  568. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  569. }
  570. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  571. }
  572. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  573. if (!empty($this->password)) {
  574. $iv = $this->_random(8);
  575. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  576. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  577. if (!class_exists('Crypt_TripleDES')) {
  578. require_once('Crypt/TripleDES.php');
  579. }
  580. $des = new Crypt_TripleDES();
  581. $des->setKey($symkey);
  582. $des->setIV($iv);
  583. $iv = strtoupper(bin2hex($iv));
  584. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  585. "Proc-Type: 4,ENCRYPTED\r\n" .
  586. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  587. "\r\n" .
  588. chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
  589. '-----END RSA PRIVATE KEY-----';
  590. } else {
  591. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  592. chunk_split(base64_encode($RSAPrivateKey)) .
  593. '-----END RSA PRIVATE KEY-----';
  594. }
  595. return $RSAPrivateKey;
  596. }
  597. }
  598. /**
  599. * Convert a public key to the appropriate format
  600. *
  601. * @access private
  602. * @see setPublicKeyFormat()
  603. * @param String $RSAPrivateKey
  604. * @return String
  605. */
  606. function _convertPublicKey($n, $e)
  607. {
  608. $modulus = $n->toBytes(true);
  609. $publicExponent = $e->toBytes(true);
  610. switch ($this->publicKeyFormat) {
  611. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  612. return array('e' => $e->copy(), 'n' => $n->copy());
  613. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  614. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  615. // string "ssh-rsa"
  616. // mpint e
  617. // mpint n
  618. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  619. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
  620. return $RSAPublicKey;
  621. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  622. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  623. // RSAPublicKey ::= SEQUENCE {
  624. // modulus INTEGER, -- n
  625. // publicExponent INTEGER -- e
  626. // }
  627. $components = array(
  628. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  629. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  630. );
  631. $RSAPublicKey = pack('Ca*a*a*',
  632. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  633. $components['modulus'], $components['publicExponent']
  634. );
  635. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  636. chunk_split(base64_encode($RSAPublicKey)) .
  637. '-----END PUBLIC KEY-----';
  638. return $RSAPublicKey;
  639. }
  640. }
  641. /**
  642. * Break a public or private key down into its constituant components
  643. *
  644. * @access private
  645. * @see _convertPublicKey()
  646. * @see _convertPrivateKey()
  647. * @param String $key
  648. * @param Integer $type
  649. * @return Array
  650. */
  651. function _parseKey($key, $type)
  652. {
  653. switch ($type) {
  654. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  655. if (!is_array($key)) {
  656. return false;
  657. }
  658. $components = array();
  659. switch (true) {
  660. case isset($key['e']):
  661. $components['publicExponent'] = $key['e']->copy();
  662. break;
  663. case isset($key['exponent']):
  664. $components['publicExponent'] = $key['exponent']->copy();
  665. break;
  666. case isset($key['publicExponent']):
  667. $components['publicExponent'] = $key['publicExponent']->copy();
  668. break;
  669. case isset($key[0]):
  670. $components['publicExponent'] = $key[0]->copy();
  671. }
  672. switch (true) {
  673. case isset($key['n']):
  674. $components['modulus'] = $key['n']->copy();
  675. break;
  676. case isset($key['modulo']):
  677. $components['modulus'] = $key['modulo']->copy();
  678. break;
  679. case isset($key['modulus']):
  680. $components['modulus'] = $key['modulus']->copy();
  681. break;
  682. case isset($key[1]):
  683. $components['modulus'] = $key[1]->copy();
  684. }
  685. return $components;
  686. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  687. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  688. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  689. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  690. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  691. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  692. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  693. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  694. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  695. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  696. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  697. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  698. implementation are part of the standard, as well.
  699. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  700. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  701. $iv = pack('H*', trim($matches[2]));
  702. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  703. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  704. $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);
  705. $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
  706. if ($ciphertext === false) {
  707. $ciphertext = $key;
  708. }
  709. switch ($matches[1]) {
  710. case 'DES-EDE3-CBC':
  711. if (!class_exists('Crypt_TripleDES')) {
  712. require_once('Crypt/TripleDES.php');
  713. }
  714. $crypto = new Crypt_TripleDES();
  715. break;
  716. case 'DES-CBC':
  717. if (!class_exists('Crypt_DES')) {
  718. require_once('Crypt/DES.php');
  719. }
  720. $crypto = new Crypt_DES();
  721. break;
  722. default:
  723. return false;
  724. }
  725. $crypto->setKey($symkey);
  726. $crypto->setIV($iv);
  727. $decoded = $crypto->decrypt($ciphertext);
  728. } else {
  729. $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);
  730. $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
  731. }
  732. if ($decoded !== false) {
  733. $key = $decoded;
  734. }
  735. $components = array();
  736. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  737. return false;
  738. }
  739. if ($this->_decodeLength($key) != strlen($key)) {
  740. return false;
  741. }
  742. $tag = ord($this->_string_shift($key));
  743. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  744. /* intended for keys for which OpenSSL's asn1parse returns the following:
  745. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  746. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  747. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  748. 17:d=2 hl=2 l= 0 prim: NULL
  749. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  750. $this->_string_shift($key, $this->_decodeLength($key));
  751. $this->_string_shift($key); // skip over the BIT STRING tag
  752. $this->_decodeLength($key); // skip over the BIT STRING length
  753. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  754. // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."
  755. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  756. $this->_string_shift($key);
  757. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  758. return false;
  759. }
  760. if ($this->_decodeLength($key) != strlen($key)) {
  761. return false;
  762. }
  763. $tag = ord($this->_string_shift($key));
  764. }
  765. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  766. return false;
  767. }
  768. $length = $this->_decodeLength($key);
  769. $temp = $this->_string_shift($key, $length);
  770. if (strlen($temp) != 1 || ord($temp) > 2) {
  771. $components['modulus'] = new Math_BigInteger($temp, -256);
  772. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  773. $length = $this->_decodeLength($key);
  774. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  775. return $components;
  776. }
  777. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  778. return false;
  779. }
  780. $length = $this->_decodeLength($key);
  781. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  782. $this->_string_shift($key);
  783. $length = $this->_decodeLength($key);
  784. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  785. $this->_string_shift($key);
  786. $length = $this->_decodeLength($key);
  787. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  788. $this->_string_shift($key);
  789. $length = $this->_decodeLength($key);
  790. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  791. $this->_string_shift($key);
  792. $length = $this->_decodeLength($key);
  793. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  794. $this->_string_shift($key);
  795. $length = $this->_decodeLength($key);
  796. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  797. $this->_string_shift($key);
  798. $length = $this->_decodeLength($key);
  799. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  800. $this->_string_shift($key);
  801. $length = $this->_decodeLength($key);
  802. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  803. if (!empty($key)) {
  804. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  805. return false;
  806. }
  807. $this->_decodeLength($key);
  808. while (!empty($key)) {
  809. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  810. return false;
  811. }
  812. $this->_decodeLength($key);
  813. $key = substr($key, 1);
  814. $length = $this->_decodeLength($key);
  815. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  816. $this->_string_shift($key);
  817. $length = $this->_decodeLength($key);
  818. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  819. $this->_string_shift($key);
  820. $length = $this->_decodeLength($key);
  821. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  822. }
  823. }
  824. return $components;
  825. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  826. $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
  827. if ($key === false) {
  828. return false;
  829. }
  830. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  831. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  832. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  833. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  834. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  835. if ($cleanup && strlen($key)) {
  836. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  837. return array(
  838. 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
  839. 'publicExponent' => $modulus
  840. );
  841. } else {
  842. return array(
  843. 'modulus' => $modulus,
  844. 'publicExponent' => $publicExponent
  845. );
  846. }
  847. }
  848. }
  849. /**
  850. * Loads a public or private key
  851. *
  852. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  853. *
  854. * @access public
  855. * @param String $key
  856. * @param Integer $type optional
  857. */
  858. function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)
  859. {
  860. $components = $this->_parseKey($key, $type);
  861. if ($components === false) {
  862. return false;
  863. }
  864. $this->modulus = $components['modulus'];
  865. $this->k = strlen($this->modulus->toBytes());
  866. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  867. if (isset($components['primes'])) {
  868. $this->primes = $components['primes'];
  869. $this->exponents = $components['exponents'];
  870. $this->coefficients = $components['coefficients'];
  871. $this->publicExponent = $components['publicExponent'];
  872. } else {
  873. $this->primes = array();
  874. $this->exponents = array();
  875. $this->coefficients = array();
  876. $this->publicExponent = false;
  877. }
  878. return true;
  879. }
  880. /**
  881. * Sets the password
  882. *
  883. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  884. * Or rather, pass in $password such that empty($password) is true.
  885. *
  886. * @see createKey()
  887. * @see loadKey()
  888. * @access public
  889. * @param String $password
  890. */
  891. function setPassword($password)
  892. {
  893. $this->password = $password;
  894. }
  895. /**
  896. * Defines the public key
  897. *
  898. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  899. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  900. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  901. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  902. * exponent this won't work unless you manually add the public exponent.
  903. *
  904. * Do note that when a new key is loaded the index will be cleared.
  905. *
  906. * Returns true on success, false on failure
  907. *
  908. * @see getPublicKey()
  909. * @access public
  910. * @param String $key
  911. * @param Integer $type optional
  912. * @return Boolean
  913. */
  914. function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  915. {
  916. $components = $this->_parseKey($key, $type);
  917. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  918. return false;
  919. }
  920. $this->publicExponent = $components['publicExponent'];
  921. }
  922. /**
  923. * Returns the public key
  924. *
  925. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  926. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  927. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  928. *
  929. * @see getPublicKey()
  930. * @access public
  931. * @param String $key
  932. * @param Integer $type optional
  933. */
  934. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  935. {
  936. if (empty($this->modulus) || empty($this->publicExponent)) {
  937. return false;
  938. }
  939. $oldFormat = $this->publicKeyFormat;
  940. $this->publicKeyFormat = $type;
  941. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  942. $this->publicKeyFormat = $oldFormat;
  943. return $temp;
  944. }
  945. /**
  946. * Generates the smallest and largest numbers requiring $bits bits
  947. *
  948. * @access private
  949. * @param Integer $bits
  950. * @return Array
  951. */
  952. function _generateMinMax($bits)
  953. {
  954. $bytes = $bits >> 3;
  955. $min = str_repeat(chr(0), $bytes);
  956. $max = str_repeat(chr(0xFF), $bytes);
  957. $msb = $bits & 7;
  958. if ($msb) {
  959. $min = chr(1 << ($msb - 1)) . $min;
  960. $max = chr((1 << $msb) - 1) . $max;
  961. } else {
  962. $min[0] = chr(0x80);
  963. }
  964. return array(
  965. 'min' => new Math_BigInteger($min, 256),
  966. 'max' => new Math_BigInteger($max, 256)
  967. );
  968. }
  969. /**
  970. * DER-decode the length
  971. *
  972. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  973. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  974. *
  975. * @access private
  976. * @param String $string
  977. * @return Integer
  978. */
  979. function _decodeLength(&$string)
  980. {
  981. $length = ord($this->_string_shift($string));
  982. if ( $length & 0x80 ) { // definite length, long form
  983. $length&= 0x7F;
  984. $temp = $this->_string_shift($string, $length);
  985. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  986. }
  987. return $length;
  988. }
  989. /**
  990. * DER-encode the length
  991. *
  992. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  993. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  994. *
  995. * @access private
  996. * @param Integer $length
  997. * @return String
  998. */
  999. function _encodeLength($length)
  1000. {
  1001. if ($length <= 0x7F) {
  1002. return chr($length);
  1003. }
  1004. $temp = ltrim(pack('N', $length), chr(0));
  1005. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1006. }
  1007. /**
  1008. * String Shift
  1009. *
  1010. * Inspired by array_shift
  1011. *
  1012. * @param String $string
  1013. * @param optional Integer $index
  1014. * @return String
  1015. * @access private
  1016. */
  1017. function _string_shift(&$string, $index = 1)
  1018. {
  1019. $substr = substr($string, 0, $index);
  1020. $string = substr($string, $index);
  1021. return $substr;
  1022. }
  1023. /**
  1024. * Determines the private key format
  1025. *
  1026. * @see createKey()
  1027. * @access public
  1028. * @param Integer $format
  1029. */
  1030. function setPrivateKeyFormat($format)
  1031. {
  1032. $this->privateKeyFormat = $format;
  1033. }
  1034. /**
  1035. * Determines the public key format
  1036. *
  1037. * @see createKey()
  1038. * @access public
  1039. * @param Integer $format
  1040. */
  1041. function setPublicKeyFormat($format)
  1042. {
  1043. $this->publicKeyFormat = $format;
  1044. }
  1045. /**
  1046. * Determines which hashing function should be used
  1047. *
  1048. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1049. * decryption. If $hash isn't supported, sha1 is used.
  1050. *
  1051. * @access public
  1052. * @param String $hash
  1053. */
  1054. function setHash($hash)
  1055. {
  1056. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1057. switch ($hash) {
  1058. case 'md2':
  1059. case 'md5':
  1060. case 'sha1':
  1061. case 'sha256':
  1062. case 'sha384':
  1063. case 'sha512':
  1064. $this->hash = new Crypt_Hash($hash);
  1065. $this->hashName = $hash;
  1066. break;
  1067. default:
  1068. $this->hash = new Crypt_Hash('sha1');
  1069. $this->hashName = 'sha1';
  1070. }
  1071. $this->hLen = $this->hash->getLength();
  1072. }
  1073. /**
  1074. * Determines which hashing function should be used for the mask generation function
  1075. *
  1076. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1077. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1078. *
  1079. * @access public
  1080. * @param String $hash
  1081. */
  1082. function setMGFHash($hash)
  1083. {
  1084. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1085. switch ($hash) {
  1086. case 'md2':
  1087. case 'md5':
  1088. case 'sha1':
  1089. case 'sha256':
  1090. case 'sha384':
  1091. case 'sha512':
  1092. $this->mgfHash = new Crypt_Hash($hash);
  1093. break;
  1094. default:
  1095. $this->mgfHash = new Crypt_Hash('sha1');
  1096. }
  1097. $this->mgfHLen = $this->mgfHash->getLength();
  1098. }
  1099. /**
  1100. * Determines the salt length
  1101. *
  1102. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1103. *
  1104. * Typical salt lengths in octets are hLen (the length of the output
  1105. * of the hash function Hash) and 0.
  1106. *
  1107. * @access public
  1108. * @param Integer $format
  1109. */
  1110. function setSaltLength($sLen)
  1111. {
  1112. $this->sLen = $sLen;
  1113. }
  1114. /**
  1115. * Generates a random string x bytes long
  1116. *
  1117. * @access public
  1118. * @param Integer $bytes
  1119. * @param optional Integer $nonzero
  1120. * @return String
  1121. */
  1122. function _random($bytes, $nonzero = false)
  1123. {
  1124. $temp = '';
  1125. if ($nonzero) {
  1126. for ($i = 0; $i < $bytes; $i++) {
  1127. $temp.= chr(crypt_random(1, 255));
  1128. }
  1129. } else {
  1130. $ints = ($bytes + 1) >> 2;
  1131. for ($i = 0; $i < $ints; $i++) {
  1132. $temp.= pack('N', crypt_random());
  1133. }
  1134. $temp = substr($temp, 0, $bytes);
  1135. }
  1136. return $temp;
  1137. }
  1138. /**
  1139. * Integer-to-Octet-String primitive
  1140. *
  1141. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1142. *
  1143. * @access private
  1144. * @param Math_BigInteger $x
  1145. * @param Integer $xLen
  1146. * @return String
  1147. */
  1148. function _i2osp($x, $xLen)
  1149. {
  1150. $x = $x->toBytes();
  1151. if (strlen($x) > $xLen) {
  1152. user_error('Integer too large', E_USER_NOTICE);
  1153. return false;
  1154. }
  1155. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1156. }
  1157. /**
  1158. * Octet-String-to-Integer primitive
  1159. *
  1160. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1161. *
  1162. * @access private
  1163. * @param String $x
  1164. * @return Math_BigInteger
  1165. */
  1166. function _os2ip($x)
  1167. {
  1168. return new Math_BigInteger($x, 256);
  1169. }
  1170. /**
  1171. * Exponentiate with or without Chinese Remainder Theorem
  1172. *
  1173. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1174. *
  1175. * @access private
  1176. * @param Math_BigInteger $x
  1177. * @return Math_BigInteger
  1178. */
  1179. function _exponentiate($x)
  1180. {
  1181. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1182. return $x->modPow($this->exponent, $this->modulus);
  1183. }
  1184. $num_primes = count($this->primes);
  1185. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1186. $m_i = array(
  1187. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1188. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1189. );
  1190. $h = $m_i[1]->subtract($m_i[2]);
  1191. $h = $h->multiply($this->coefficients[2]);
  1192. list(, $h) = $h->divide($this->primes[1]);
  1193. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1194. $r = $this->primes[1];
  1195. for ($i = 3; $i <= $num_primes; $i++) {
  1196. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1197. $r = $r->multiply($this->primes[$i - 1]);
  1198. $h = $m_i->subtract($m);
  1199. $h = $h->multiply($this->coefficients[$i]);
  1200. list(, $h) = $h->divide($this->primes[$i]);
  1201. $m = $m->add($r->multiply($h));
  1202. }
  1203. } else {
  1204. $smallest = $this->primes[1];
  1205. for ($i = 2; $i <= $num_primes; $i++) {
  1206. if ($smallest->compare($this->primes[$i]) > 0) {
  1207. $smallest = $this->primes[$i];
  1208. }
  1209. }
  1210. $one = new Math_BigInteger(1);
  1211. $one->setRandomGenerator('crypt_random');
  1212. $r = $one->random($one, $smallest->subtract($one));
  1213. $m_i = array(
  1214. 1 => $this->_blind($x, $r, 1),
  1215. 2 => $this->_blind($x, $r, 2)
  1216. );
  1217. $h = $m_i[1]->subtract($m_i[2]);
  1218. $h = $h->multiply($this->coefficients[2]);
  1219. list(, $h) = $h->divide($this->primes[1]);
  1220. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1221. $r = $this->primes[1];
  1222. for ($i = 3; $i <= $num_primes; $i++) {
  1223. $m_i = $this->_blind($x, $r, $i);
  1224. $r = $r->multiply($this->primes[$i - 1]);
  1225. $h = $m_i->subtract($m);
  1226. $h = $h->multiply($this->coefficients[$i]);
  1227. list(, $h) = $h->divide($this->primes[$i]);
  1228. $m = $m->add($r->multiply($h));
  1229. }
  1230. }
  1231. return $m;
  1232. }
  1233. /**
  1234. * Performs RSA Blinding
  1235. *
  1236. * Protects against timing attacks by employing RSA Blinding.
  1237. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1238. *
  1239. * @access private
  1240. * @param Math_BigInteger $x
  1241. * @param Math_BigInteger $r
  1242. * @param Integer $i
  1243. * @return Math_BigInteger
  1244. */
  1245. function _blind($x, $r, $i)
  1246. {
  1247. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1248. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1249. $r = $r->modInverse($this->primes[$i]);
  1250. $x = $x->multiply($r);
  1251. list(, $x) = $x->divide($this->primes[$i]);
  1252. return $x;
  1253. }
  1254. /**
  1255. * RSAEP
  1256. *
  1257. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1258. *
  1259. * @access private
  1260. * @param Math_BigInteger $m
  1261. * @return Math_BigInteger
  1262. */
  1263. function _rsaep($m)
  1264. {
  1265. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  1266. user_error('Message representative out of range', E_USER_NOTICE);
  1267. return false;
  1268. }
  1269. return $this->_exponentiate($m);
  1270. }
  1271. /**
  1272. * RSADP
  1273. *
  1274. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  1275. *
  1276. * @access private
  1277. * @param Math_BigInteger $c
  1278. * @return Math_BigInteger
  1279. */
  1280. function _rsadp($c)
  1281. {

Large files files are truncated, but you can click here to view the full file