PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/Crypt/RSA.php

https://github.com/purare/spotweb
PHP | 2142 lines | 1040 code | 224 blank | 878 comment | 167 complexity | 498dff1ab595217034fe96b5e4e3d9d3 MD5 | raw file
Possible License(s): GPL-2.0

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.opensource.org/licenses/mit-license.html MIT License
  64. * @version $Id: RSA.php,v 1.19 2010/09/12 21:58:54 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 array(
  453. 'privatekey' => '',
  454. 'publickey' => '',
  455. 'partialkey' => serialize(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. if (count($primes) > 1) {
  475. $partialkey = '';
  476. } else {
  477. array_pop($primes);
  478. $partialkey = serialize(array(
  479. 'primes' => $primes,
  480. 'coefficients' => $coefficients,
  481. 'lcm' => $lcm,
  482. 'exponents' => $exponents
  483. ));
  484. }
  485. return array(
  486. 'privatekey' => '',
  487. 'publickey' => '',
  488. 'partialkey' => $partialkey
  489. );
  490. }
  491. // the first coefficient is calculated differently from the rest
  492. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  493. if ($i > 2) {
  494. $coefficients[$i] = $n->modInverse($primes[$i]);
  495. }
  496. $n = $n->multiply($primes[$i]);
  497. $temp = $primes[$i]->subtract($this->one);
  498. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  499. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  500. $lcm['top'] = $lcm['top']->multiply($temp);
  501. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  502. $exponents[$i] = $e->modInverse($temp);
  503. }
  504. list($lcm) = $lcm['top']->divide($lcm['bottom']);
  505. $gcd = $lcm->gcd($e);
  506. $i0 = 1;
  507. } while (!$gcd->equals($this->one));
  508. $d = $e->modInverse($lcm);
  509. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  510. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  511. // RSAPrivateKey ::= SEQUENCE {
  512. // version Version,
  513. // modulus INTEGER, -- n
  514. // publicExponent INTEGER, -- e
  515. // privateExponent INTEGER, -- d
  516. // prime1 INTEGER, -- p
  517. // prime2 INTEGER, -- q
  518. // exponent1 INTEGER, -- d mod (p-1)
  519. // exponent2 INTEGER, -- d mod (q-1)
  520. // coefficient INTEGER, -- (inverse of q) mod p
  521. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  522. // }
  523. return array(
  524. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  525. 'publickey' => $this->_convertPublicKey($n, $e),
  526. 'partialkey' => false
  527. );
  528. }
  529. /**
  530. * Convert a private key to the appropriate format.
  531. *
  532. * @access private
  533. * @see setPrivateKeyFormat()
  534. * @param String $RSAPrivateKey
  535. * @return String
  536. */
  537. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  538. {
  539. $num_primes = count($primes);
  540. $raw = array(
  541. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  542. 'modulus' => $n->toBytes(true),
  543. 'publicExponent' => $e->toBytes(true),
  544. 'privateExponent' => $d->toBytes(true),
  545. 'prime1' => $primes[1]->toBytes(true),
  546. 'prime2' => $primes[2]->toBytes(true),
  547. 'exponent1' => $exponents[1]->toBytes(true),
  548. 'exponent2' => $exponents[2]->toBytes(true),
  549. 'coefficient' => $coefficients[2]->toBytes(true)
  550. );
  551. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  552. // call _convertPublicKey() instead.
  553. switch ($this->privateKeyFormat) {
  554. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  555. $components = array();
  556. foreach ($raw as $name => $value) {
  557. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  558. }
  559. $RSAPrivateKey = implode('', $components);
  560. if ($num_primes > 2) {
  561. $OtherPrimeInfos = '';
  562. for ($i = 3; $i <= $num_primes; $i++) {
  563. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  564. //
  565. // OtherPrimeInfo ::= SEQUENCE {
  566. // prime INTEGER, -- ri
  567. // exponent INTEGER, -- di
  568. // coefficient INTEGER -- ti
  569. // }
  570. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  571. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  572. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  573. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  574. }
  575. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  576. }
  577. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  578. if (!empty($this->password)) {
  579. $iv = $this->_random(8);
  580. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  581. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  582. if (!class_exists('Crypt_TripleDES')) {
  583. require_once('Crypt/TripleDES.php');
  584. }
  585. $des = new Crypt_TripleDES();
  586. $des->setKey($symkey);
  587. $des->setIV($iv);
  588. $iv = strtoupper(bin2hex($iv));
  589. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  590. "Proc-Type: 4,ENCRYPTED\r\n" .
  591. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  592. "\r\n" .
  593. chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
  594. '-----END RSA PRIVATE KEY-----';
  595. } else {
  596. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  597. chunk_split(base64_encode($RSAPrivateKey)) .
  598. '-----END RSA PRIVATE KEY-----';
  599. }
  600. return $RSAPrivateKey;
  601. }
  602. }
  603. /**
  604. * Convert a public key to the appropriate format
  605. *
  606. * @access private
  607. * @see setPublicKeyFormat()
  608. * @param String $RSAPrivateKey
  609. * @return String
  610. */
  611. function _convertPublicKey($n, $e)
  612. {
  613. $modulus = $n->toBytes(true);
  614. $publicExponent = $e->toBytes(true);
  615. switch ($this->publicKeyFormat) {
  616. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  617. return array('e' => $e->copy(), 'n' => $n->copy());
  618. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  619. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  620. // string "ssh-rsa"
  621. // mpint e
  622. // mpint n
  623. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  624. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
  625. return $RSAPublicKey;
  626. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  627. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  628. // RSAPublicKey ::= SEQUENCE {
  629. // modulus INTEGER, -- n
  630. // publicExponent INTEGER -- e
  631. // }
  632. $components = array(
  633. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  634. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  635. );
  636. $RSAPublicKey = pack('Ca*a*a*',
  637. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  638. $components['modulus'], $components['publicExponent']
  639. );
  640. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  641. chunk_split(base64_encode($RSAPublicKey)) .
  642. '-----END PUBLIC KEY-----';
  643. return $RSAPublicKey;
  644. }
  645. }
  646. /**
  647. * Break a public or private key down into its constituant components
  648. *
  649. * @access private
  650. * @see _convertPublicKey()
  651. * @see _convertPrivateKey()
  652. * @param String $key
  653. * @param Integer $type
  654. * @return Array
  655. */
  656. function _parseKey($key, $type)
  657. {
  658. switch ($type) {
  659. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  660. if (!is_array($key)) {
  661. return false;
  662. }
  663. $components = array();
  664. switch (true) {
  665. case isset($key['e']):
  666. $components['publicExponent'] = $key['e']->copy();
  667. break;
  668. case isset($key['exponent']):
  669. $components['publicExponent'] = $key['exponent']->copy();
  670. break;
  671. case isset($key['publicExponent']):
  672. $components['publicExponent'] = $key['publicExponent']->copy();
  673. break;
  674. case isset($key[0]):
  675. $components['publicExponent'] = $key[0]->copy();
  676. }
  677. switch (true) {
  678. case isset($key['n']):
  679. $components['modulus'] = $key['n']->copy();
  680. break;
  681. case isset($key['modulo']):
  682. $components['modulus'] = $key['modulo']->copy();
  683. break;
  684. case isset($key['modulus']):
  685. $components['modulus'] = $key['modulus']->copy();
  686. break;
  687. case isset($key[1]):
  688. $components['modulus'] = $key[1]->copy();
  689. }
  690. return $components;
  691. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  692. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  693. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  694. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  695. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  696. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  697. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  698. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  699. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  700. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  701. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  702. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  703. implementation are part of the standard, as well.
  704. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  705. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  706. $iv = pack('H*', trim($matches[2]));
  707. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  708. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  709. $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);
  710. $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
  711. if ($ciphertext === false) {
  712. $ciphertext = $key;
  713. }
  714. switch ($matches[1]) {
  715. case 'AES-128-CBC':
  716. if (!class_exists('Crypt_AES')) {
  717. require_once('Crypt/AES.php');
  718. }
  719. $symkey = substr($symkey, 0, 16);
  720. break;
  721. case 'DES-EDE3-CFB':
  722. if (!class_exists('Crypt_TripleDES')) {
  723. require_once('Crypt/TripleDES.php');
  724. }
  725. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  726. break;
  727. case 'DES-EDE3-CBC':
  728. if (!class_exists('Crypt_TripleDES')) {
  729. require_once('Crypt/TripleDES.php');
  730. }
  731. $crypto = new Crypt_TripleDES();
  732. break;
  733. case 'DES-CBC':
  734. if (!class_exists('Crypt_DES')) {
  735. require_once('Crypt/DES.php');
  736. }
  737. $crypto = new Crypt_DES();
  738. break;
  739. default:
  740. return false;
  741. }
  742. $crypto->setKey($symkey);
  743. $crypto->setIV($iv);
  744. $decoded = $crypto->decrypt($ciphertext);
  745. } else {
  746. $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);
  747. $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
  748. }
  749. if ($decoded !== false) {
  750. $key = $decoded;
  751. }
  752. $components = array();
  753. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  754. return false;
  755. }
  756. if ($this->_decodeLength($key) != strlen($key)) {
  757. return false;
  758. }
  759. $tag = ord($this->_string_shift($key));
  760. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  761. /* intended for keys for which OpenSSL's asn1parse returns the following:
  762. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  763. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  764. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  765. 17:d=2 hl=2 l= 0 prim: NULL
  766. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  767. $this->_string_shift($key, $this->_decodeLength($key));
  768. $this->_string_shift($key); // skip over the BIT STRING tag
  769. $this->_decodeLength($key); // skip over the BIT STRING length
  770. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  771. // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."
  772. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  773. $this->_string_shift($key);
  774. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  775. return false;
  776. }
  777. if ($this->_decodeLength($key) != strlen($key)) {
  778. return false;
  779. }
  780. $tag = ord($this->_string_shift($key));
  781. }
  782. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  783. return false;
  784. }
  785. $length = $this->_decodeLength($key);
  786. $temp = $this->_string_shift($key, $length);
  787. if (strlen($temp) != 1 || ord($temp) > 2) {
  788. $components['modulus'] = new Math_BigInteger($temp, -256);
  789. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  790. $length = $this->_decodeLength($key);
  791. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  792. return $components;
  793. }
  794. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  795. return false;
  796. }
  797. $length = $this->_decodeLength($key);
  798. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  799. $this->_string_shift($key);
  800. $length = $this->_decodeLength($key);
  801. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  802. $this->_string_shift($key);
  803. $length = $this->_decodeLength($key);
  804. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  805. $this->_string_shift($key);
  806. $length = $this->_decodeLength($key);
  807. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  808. $this->_string_shift($key);
  809. $length = $this->_decodeLength($key);
  810. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  811. $this->_string_shift($key);
  812. $length = $this->_decodeLength($key);
  813. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  814. $this->_string_shift($key);
  815. $length = $this->_decodeLength($key);
  816. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  817. $this->_string_shift($key);
  818. $length = $this->_decodeLength($key);
  819. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  820. if (!empty($key)) {
  821. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  822. return false;
  823. }
  824. $this->_decodeLength($key);
  825. while (!empty($key)) {
  826. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  827. return false;
  828. }
  829. $this->_decodeLength($key);
  830. $key = substr($key, 1);
  831. $length = $this->_decodeLength($key);
  832. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  833. $this->_string_shift($key);
  834. $length = $this->_decodeLength($key);
  835. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  836. $this->_string_shift($key);
  837. $length = $this->_decodeLength($key);
  838. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  839. }
  840. }
  841. return $components;
  842. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  843. $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
  844. if ($key === false) {
  845. return false;
  846. }
  847. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  848. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  849. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  850. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  851. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  852. if ($cleanup && strlen($key)) {
  853. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  854. return array(
  855. 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
  856. 'publicExponent' => $modulus
  857. );
  858. } else {
  859. return array(
  860. 'modulus' => $modulus,
  861. 'publicExponent' => $publicExponent
  862. );
  863. }
  864. }
  865. }
  866. /**
  867. * Loads a public or private key
  868. *
  869. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  870. *
  871. * @access public
  872. * @param String $key
  873. * @param Integer $type optional
  874. */
  875. function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)
  876. {
  877. $components = $this->_parseKey($key, $type);
  878. if ($components === false) {
  879. return false;
  880. }
  881. $this->modulus = $components['modulus'];
  882. $this->k = strlen($this->modulus->toBytes());
  883. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  884. if (isset($components['primes'])) {
  885. $this->primes = $components['primes'];
  886. $this->exponents = $components['exponents'];
  887. $this->coefficients = $components['coefficients'];
  888. $this->publicExponent = $components['publicExponent'];
  889. } else {
  890. $this->primes = array();
  891. $this->exponents = array();
  892. $this->coefficients = array();
  893. $this->publicExponent = false;
  894. }
  895. return true;
  896. }
  897. /**
  898. * Sets the password
  899. *
  900. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  901. * Or rather, pass in $password such that empty($password) is true.
  902. *
  903. * @see createKey()
  904. * @see loadKey()
  905. * @access public
  906. * @param String $password
  907. */
  908. function setPassword($password)
  909. {
  910. $this->password = $password;
  911. }
  912. /**
  913. * Defines the public key
  914. *
  915. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  916. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  917. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  918. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  919. * exponent this won't work unless you manually add the public exponent.
  920. *
  921. * Do note that when a new key is loaded the index will be cleared.
  922. *
  923. * Returns true on success, false on failure
  924. *
  925. * @see getPublicKey()
  926. * @access public
  927. * @param String $key
  928. * @param Integer $type optional
  929. * @return Boolean
  930. */
  931. function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  932. {
  933. $components = $this->_parseKey($key, $type);
  934. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  935. user_error('Trying to load a public key? Use loadKey() instead. It\'s called loadKey() and not loadPrivateKey() for a reason.', E_USER_NOTICE);
  936. return false;
  937. }
  938. $this->publicExponent = $components['publicExponent'];
  939. return true;
  940. }
  941. /**
  942. * Returns the public key
  943. *
  944. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  945. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  946. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  947. *
  948. * @see getPublicKey()
  949. * @access public
  950. * @param String $key
  951. * @param Integer $type optional
  952. */
  953. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  954. {
  955. if (empty($this->modulus) || empty($this->publicExponent)) {
  956. return false;
  957. }
  958. $oldFormat = $this->publicKeyFormat;
  959. $this->publicKeyFormat = $type;
  960. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  961. $this->publicKeyFormat = $oldFormat;
  962. return $temp;
  963. }
  964. /**
  965. * Generates the smallest and largest numbers requiring $bits bits
  966. *
  967. * @access private
  968. * @param Integer $bits
  969. * @return Array
  970. */
  971. function _generateMinMax($bits)
  972. {
  973. $bytes = $bits >> 3;
  974. $min = str_repeat(chr(0), $bytes);
  975. $max = str_repeat(chr(0xFF), $bytes);
  976. $msb = $bits & 7;
  977. if ($msb) {
  978. $min = chr(1 << ($msb - 1)) . $min;
  979. $max = chr((1 << $msb) - 1) . $max;
  980. } else {
  981. $min[0] = chr(0x80);
  982. }
  983. return array(
  984. 'min' => new Math_BigInteger($min, 256),
  985. 'max' => new Math_BigInteger($max, 256)
  986. );
  987. }
  988. /**
  989. * DER-decode 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 String $string
  996. * @return Integer
  997. */
  998. function _decodeLength(&$string)
  999. {
  1000. $length = ord($this->_string_shift($string));
  1001. if ( $length & 0x80 ) { // definite length, long form
  1002. $length&= 0x7F;
  1003. $temp = $this->_string_shift($string, $length);
  1004. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1005. }
  1006. return $length;
  1007. }
  1008. /**
  1009. * DER-encode the length
  1010. *
  1011. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1012. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  1013. *
  1014. * @access private
  1015. * @param Integer $length
  1016. * @return String
  1017. */
  1018. function _encodeLength($length)
  1019. {
  1020. if ($length <= 0x7F) {
  1021. return chr($length);
  1022. }
  1023. $temp = ltrim(pack('N', $length), chr(0));
  1024. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1025. }
  1026. /**
  1027. * String Shift
  1028. *
  1029. * Inspired by array_shift
  1030. *
  1031. * @param String $string
  1032. * @param optional Integer $index
  1033. * @return String
  1034. * @access private
  1035. */
  1036. function _string_shift(&$string, $index = 1)
  1037. {
  1038. $substr = substr($string, 0, $index);
  1039. $string = substr($string, $index);
  1040. return $substr;
  1041. }
  1042. /**
  1043. * Determines the private key format
  1044. *
  1045. * @see createKey()
  1046. * @access public
  1047. * @param Integer $format
  1048. */
  1049. function setPrivateKeyFormat($format)
  1050. {
  1051. $this->privateKeyFormat = $format;
  1052. }
  1053. /**
  1054. * Determines the public key format
  1055. *
  1056. * @see createKey()
  1057. * @access public
  1058. * @param Integer $format
  1059. */
  1060. function setPublicKeyFormat($format)
  1061. {
  1062. $this->publicKeyFormat = $format;
  1063. }
  1064. /**
  1065. * Determines which hashing function should be used
  1066. *
  1067. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1068. * decryption. If $hash isn't supported, sha1 is used.
  1069. *
  1070. * @access public
  1071. * @param String $hash
  1072. */
  1073. function setHash($hash)
  1074. {
  1075. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1076. switch ($hash) {
  1077. case 'md2':
  1078. case 'md5':
  1079. case 'sha1':
  1080. case 'sha256':
  1081. case 'sha384':
  1082. case 'sha512':
  1083. $this->hash = new Crypt_Hash($hash);
  1084. $this->hashName = $hash;
  1085. break;
  1086. default:
  1087. $this->hash = new Crypt_Hash('sha1');
  1088. $this->hashName = 'sha1';
  1089. }
  1090. $this->hLen = $this->hash->getLength();
  1091. }
  1092. /**
  1093. * Determines which hashing function should be used for the mask generation function
  1094. *
  1095. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1096. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1097. *
  1098. * @access public
  1099. * @param String $hash
  1100. */
  1101. function setMGFHash($hash)
  1102. {
  1103. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1104. switch ($hash) {
  1105. case 'md2':
  1106. case 'md5':
  1107. case 'sha1':
  1108. case 'sha256':
  1109. case 'sha384':
  1110. case 'sha512':
  1111. $this->mgfHash = new Crypt_Hash($hash);
  1112. break;
  1113. default:
  1114. $this->mgfHash = new Crypt_Hash('sha1');
  1115. }
  1116. $this->mgfHLen = $this->mgfHash->getLength();
  1117. }
  1118. /**
  1119. * Determines the salt length
  1120. *
  1121. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1122. *
  1123. * Typical salt lengths in octets are hLen (the length of the output
  1124. * of the hash function Hash) and 0.
  1125. *
  1126. * @access public
  1127. * @param Integer $format
  1128. */
  1129. function setSaltLength($sLen)
  1130. {
  1131. $this->sLen = $sLen;
  1132. }
  1133. /**
  1134. * Generates a random string x bytes long
  1135. *
  1136. * @access public
  1137. * @param Integer $bytes
  1138. * @param optional Integer $nonzero
  1139. * @return String
  1140. */
  1141. function _random($bytes, $nonzero = false)
  1142. {
  1143. $temp = '';
  1144. if ($nonzero) {
  1145. for ($i = 0; $i < $bytes; $i++) {
  1146. $temp.= chr(crypt_random(1, 255));
  1147. }
  1148. } else {
  1149. $ints = ($bytes + 1) >> 2;
  1150. for ($i = 0; $i < $ints; $i++) {
  1151. $temp.= pack('N', crypt_random());
  1152. }
  1153. $temp = substr($temp, 0, $bytes);
  1154. }
  1155. return $temp;
  1156. }
  1157. /**
  1158. * Integer-to-Octet-String primitive
  1159. *
  1160. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1161. *
  1162. * @access private
  1163. * @param Math_BigInteger $x
  1164. * @param Integer $xLen
  1165. * @return String
  1166. */
  1167. function _i2osp($x, $xLen)
  1168. {
  1169. $x = $x->toBytes();
  1170. if (strlen($x) > $xLen) {
  1171. user_error('Integer too large', E_USER_NOTICE);
  1172. return false;
  1173. }
  1174. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1175. }
  1176. /**
  1177. * Octet-String-to-Integer primitive
  1178. *
  1179. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1180. *
  1181. * @access private
  1182. * @param String $x
  1183. * @return Math_BigInteger
  1184. */
  1185. function _os2ip($x)
  1186. {
  1187. return new Math_BigInteger($x, 256);
  1188. }
  1189. /**
  1190. * Exponentiate with or without Chinese Remainder Theorem
  1191. *
  1192. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1193. *
  1194. * @access private
  1195. * @param Math_BigInteger $x
  1196. * @return Math_BigInteger
  1197. */
  1198. function _exponentiate($x)
  1199. {
  1200. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1201. return $x->modPow($this->exponent, $this->modulus);
  1202. }
  1203. $num_primes = count($this->primes);
  1204. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1205. $m_i = array(
  1206. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1207. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1208. );
  1209. $h = $m_i[1]->subtract($m_i[2]);
  1210. $h = $h->multiply($this->coefficients[2]);
  1211. list(, $h) = $h->divide($this->primes[1]);
  1212. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1213. $r = $this->primes[1];
  1214. for ($i = 3; $i <= $num_primes; $i++) {
  1215. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1216. $r = $r->multiply($this->primes[$i - 1]);
  1217. $h = $m_i->subtract($m);
  1218. $h = $h->multiply($this->coefficients[$i]);
  1219. list(, $h) = $h->divide($this->primes[$i]);
  1220. $m = $m->add($r->multiply($h));
  1221. }
  1222. } else {
  1223. $smallest = $this->primes[1];
  1224. for ($i = 2; $i <= $num_primes; $i++) {
  1225. if ($smallest->compare($this->primes[$i]) > 0) {
  1226. $smallest = $this->primes[$i];
  1227. }
  1228. }
  1229. $one = new Math_BigInteger(1);
  1230. $one->setRandomGenerator('crypt_random');
  1231. $r = $one->random($one, $smallest->subtract($one));
  1232. $m_i = array(
  1233. 1 => $this->_blind($x, $r, 1),
  1234. 2 => $this->_blind($x, $r, 2)
  1235. );
  1236. $h = $m_i[1]->subtract($m_i[2]);
  1237. $h = $h->multiply($this->coefficients[2]);
  1238. list(, $h) = $h->divide($this->primes[1]);
  1239. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1240. $r = $this->primes[1];
  1241. for ($i = 3; $i <= $num_primes; $i++) {
  1242. $m_i = $this->_blind($x, $r, $i);
  1243. $r = $r->multiply($this->primes[$i - 1]);
  1244. $h = $m_i->subtract($m);
  1245. $h = $h->multiply($this->coefficients[$i]);
  1246. list(, $h) = $h->divide($this->primes[$i]);
  1247. $m = $m->add($r->multiply($h));
  1248. }
  1249. }
  1250. return $m;
  1251. }
  1252. /**
  1253. * Performs RSA Blinding
  1254. *
  1255. * Protects against timing attacks by employing RSA Blinding.
  1256. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1257. *
  1258. * @access private
  1259. * @param Math_BigInteger $x
  1260. * @param Math_BigInteger $r
  1261. * @param Integer $i
  1262. * @return Math_BigInteger
  1263. */
  1264. function _blind($x, $r, $i)
  1265. {
  1266. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1267. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1268. $r = $r->modInverse($this->primes[$i]);
  1269. $x = $x->multiply($r);
  1270. list(, $x) = $x->divide($this->primes[$i]);
  1271. return $x;
  1272. }
  1273. /**
  1274. * RSAEP
  1275. *
  1276. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1277. *
  1278. * @access private
  1279. * @param Math_BigInteger $m
  1280. * @return Math_BigInteger
  1281. */
  1282. function _rsaep($m)
  1283. {
  1284. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  1285. user_error('Message representative out of range', E_USER_NOTICE);
  1286. return false;
  1287. }
  1288. return $this->_exponentiate($m);
  1289. }
  1290. /**
  1291. * RSADP
  1292. *
  1293. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  1294. *
  1295. * @access private
  1296. * @param Math_BigInteger $c
  1297. * @return Math_BigInteger
  1298. */
  1299. function _rsadp($c)
  1300. {
  1301. if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
  1302. user_error('Ciphertext representative out of range', E_USER_NOTICE);
  1303. return false;
  1304. }
  1305. return $this->_exponentiate($c);
  1306. }
  1307. /**
  1308. * RSASP1
  1309. *
  1310. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  1311. *
  1312. * @access private
  1313. …

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