PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/src/lib/phpseclib/Crypt/RSA.php

https://bitbucket.org/mkrasuski/magento-ce
PHP | 2119 lines | 1020 code | 221 blank | 878 comment | 163 complexity | 579c11f7b2e05cae01b67b31461ca264 MD5 | raw file

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

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