PageRenderTime 1370ms CodeModel.GetById 46ms RepoModel.GetById 4ms app.codeStats 1ms

/Crypt/RSA.php

http://github.com/spotweb/spotweb
PHP | 1935 lines | 922 code | 200 blank | 813 comment | 154 complexity | 3cd2e7e39e3d87fbc6645f176464e784 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0, Apache-2.0, LGPL-3.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. /* We peek a little forwards, if an sequence follows the integer field,
  786. there is some additional padding we need to strip */
  787. if (ord(substr($key, 2, 1)) == CRYPT_RSA_ASN1_SEQUENCE) {
  788. /*
  789. intended for keys for which openssl's asn1parse returns the following:
  790. 0:d=0 hl=4 l= 631 cons: SEQUENCE
  791. 4:d=1 hl=2 l= 1 prim: INTEGER :00
  792. 7:d=1 hl=2 l= 13 cons: SEQUENCE
  793. 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  794. 20:d=2 hl=2 l= 0 prim: NULL
  795. 22:d=1 hl=4 l= 609 prim: OCTET STRING [HEX DUMP]
  796. */
  797. $tag = ord($this->_string_shift($key, $this->_decodeLength($key)));
  798. /* Read the sequence with the object in it */
  799. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  800. return false;
  801. }
  802. /* skip over the rsaEncryption object and over the trailing NULL */
  803. $encLength = $this->_decodeLength($key);
  804. $this->_string_shift($key, $encLength);
  805. if (ord($this->_string_shift($key)) != 4) { /* skip over the OCTET STRING tag */
  806. return false;
  807. } # if
  808. $this->_decodeLength($key); // skip over the OCTET STRING length
  809. /* Inside this package we will find another ASN1 sequence and length,
  810. because at this time in the parser, it is expected to be beyond this,
  811. skip it */
  812. $this->_string_shift($key); // skip over the sequence tag
  813. $this->_decodeLength($key); // skip over the sequence length
  814. $tag = ord($this->_string_shift($key));
  815. } # if
  816. $length = $this->_decodeLength($key);
  817. $temp = $this->_string_shift($key, $length);
  818. if (strlen($temp) != 1 || ord($temp) > 2) {
  819. $components['modulus'] = new Math_BigInteger($temp, -256);
  820. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  821. $length = $this->_decodeLength($key);
  822. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  823. return $components;
  824. }
  825. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  826. return false;
  827. }
  828. $length = $this->_decodeLength($key);
  829. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  830. $this->_string_shift($key);
  831. $length = $this->_decodeLength($key);
  832. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  833. $this->_string_shift($key);
  834. $length = $this->_decodeLength($key);
  835. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  836. $this->_string_shift($key);
  837. $length = $this->_decodeLength($key);
  838. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  839. $this->_string_shift($key);
  840. $length = $this->_decodeLength($key);
  841. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  842. $this->_string_shift($key);
  843. $length = $this->_decodeLength($key);
  844. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  845. $this->_string_shift($key);
  846. $length = $this->_decodeLength($key);
  847. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  848. $this->_string_shift($key);
  849. $length = $this->_decodeLength($key);
  850. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  851. if (!empty($key)) {
  852. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  853. return false;
  854. }
  855. $this->_decodeLength($key);
  856. while (!empty($key)) {
  857. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  858. return false;
  859. }
  860. $this->_decodeLength($key);
  861. $key = substr($key, 1);
  862. $length = $this->_decodeLength($key);
  863. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  864. $this->_string_shift($key);
  865. $length = $this->_decodeLength($key);
  866. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  867. $this->_string_shift($key);
  868. $length = $this->_decodeLength($key);
  869. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  870. }
  871. }
  872. return $components;
  873. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  874. $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
  875. if ($key === false) {
  876. return false;
  877. }
  878. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  879. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  880. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  881. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  882. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  883. if ($cleanup && strlen($key)) {
  884. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  885. return array(
  886. 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
  887. 'publicExponent' => $modulus
  888. );
  889. } else {
  890. return array(
  891. 'modulus' => $modulus,
  892. 'publicExponent' => $publicExponent
  893. );
  894. }
  895. }
  896. }
  897. /**
  898. * Loads a public or private key
  899. *
  900. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  901. *
  902. * @access public
  903. * @param String $key
  904. * @param Integer $type optional
  905. */
  906. function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)
  907. {
  908. $components = $this->_parseKey($key, $type);
  909. if ($components === false) {
  910. return false;
  911. }
  912. $this->modulus = $components['modulus'];
  913. $this->k = strlen($this->modulus->toBytes());
  914. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  915. if (isset($components['primes'])) {
  916. $this->primes = $components['primes'];
  917. $this->exponents = $components['exponents'];
  918. $this->coefficients = $components['coefficients'];
  919. $this->publicExponent = $components['publicExponent'];
  920. } else {
  921. $this->primes = array();
  922. $this->exponents = array();
  923. $this->coefficients = array();
  924. $this->publicExponent = false;
  925. }
  926. return true;
  927. }
  928. /**
  929. * Sets the password
  930. *
  931. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  932. * Or rather, pass in $password such that empty($password) is true.
  933. *
  934. * @see createKey()
  935. * @see loadKey()
  936. * @access public
  937. * @param String $password
  938. */
  939. function setPassword($password)
  940. {
  941. $this->password = $password;
  942. }
  943. /**
  944. * Defines the public key
  945. *
  946. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  947. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  948. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  949. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  950. * exponent this won't work unless you manually add the public exponent.
  951. *
  952. * Do note that when a new key is loaded the index will be cleared.
  953. *
  954. * Returns true on success, false on failure
  955. *
  956. * @see getPublicKey()
  957. * @access public
  958. * @param String $key
  959. * @param Integer $type optional
  960. * @return Boolean
  961. */
  962. function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  963. {
  964. $components = $this->_parseKey($key, $type);
  965. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  966. user_error('Trying to load a public key? Use loadKey() instead. It\'s called loadKey() and not loadPrivateKey() for a reason.', E_USER_NOTICE);
  967. return false;
  968. }
  969. $this->publicExponent = $components['publicExponent'];
  970. return true;
  971. }
  972. /**
  973. * Returns the public key
  974. *
  975. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  976. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  977. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  978. *
  979. * @see getPublicKey()
  980. * @access public
  981. * @param String $key
  982. * @param Integer $type optional
  983. */
  984. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  985. {
  986. if (empty($this->modulus) || empty($this->publicExponent)) {
  987. return false;
  988. }
  989. $oldFormat = $this->publicKeyFormat;
  990. $this->publicKeyFormat = $type;
  991. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  992. $this->publicKeyFormat = $oldFormat;
  993. return $temp;
  994. }
  995. /**
  996. * Generates the smallest and largest numbers requiring $bits bits
  997. *
  998. * @access private
  999. * @param Integer $bits
  1000. * @return Array
  1001. */
  1002. function _generateMinMax($bits)
  1003. {
  1004. $bytes = $bits >> 3;
  1005. $min = str_repeat(chr(0), $bytes);
  1006. $max = str_repeat(chr(0xFF), $bytes);
  1007. $msb = $bits & 7;
  1008. if ($msb) {
  1009. $min = chr(1 << ($msb - 1)) . $min;
  1010. $max = chr((1 << $msb) - 1) . $max;
  1011. } else {
  1012. $min[0] = chr(0x80);
  1013. }
  1014. return array(
  1015. 'min' => new Math_BigInteger($min, 256),
  1016. 'max' => new Math_BigInteger($max, 256)
  1017. );
  1018. }
  1019. /**
  1020. * DER-decode the length
  1021. *
  1022. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1023. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  1024. *
  1025. * @access private
  1026. * @param String $string
  1027. * @return Integer
  1028. */
  1029. function _decodeLength(&$string)
  1030. {
  1031. $length = ord($this->_string_shift($string));
  1032. if ( $length & 0x80 ) { // definite length, long form
  1033. $length&= 0x7F;
  1034. $temp = $this->_string_shift($string, $length);
  1035. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1036. }
  1037. return $length;
  1038. }
  1039. /**
  1040. * DER-encode the length
  1041. *
  1042. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1043. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  1044. *
  1045. * @access private
  1046. * @param Integer $length
  1047. * @return String
  1048. */
  1049. function _encodeLength($length)
  1050. {
  1051. if ($length <= 0x7F) {
  1052. return chr($length);
  1053. }
  1054. $temp = ltrim(pack('N', $length), chr(0));
  1055. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1056. }
  1057. /**
  1058. * String Shift
  1059. *
  1060. * Inspired by array_shift
  1061. *
  1062. * @param String $string
  1063. * @param optional Integer $index
  1064. * @return String
  1065. * @access private
  1066. */
  1067. function _string_shift(&$string, $index = 1)
  1068. {
  1069. $substr = substr($string, 0, $index);
  1070. $string = substr($string, $index);
  1071. return $substr;
  1072. }
  1073. /**
  1074. * Determines the private key format
  1075. *
  1076. * @see createKey()
  1077. * @access public
  1078. * @param Integer $format
  1079. */
  1080. function setPrivateKeyFormat($format)
  1081. {
  1082. $this->privateKeyFormat = $format;
  1083. }
  1084. /**
  1085. * Determines the public key format
  1086. *
  1087. * @see createKey()
  1088. * @access public
  1089. * @param Integer $format
  1090. */
  1091. function setPublicKeyFormat($format)
  1092. {
  1093. $this->publicKeyFormat = $format;
  1094. }
  1095. /**
  1096. * Determines which hashing function should be used
  1097. *
  1098. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1099. * decryption. If $hash isn't supported, sha1 is used.
  1100. *
  1101. * @access public
  1102. * @param String $hash
  1103. */
  1104. function setHash($hash)
  1105. {
  1106. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1107. switch ($hash) {
  1108. case 'md2':
  1109. case 'md5':
  1110. case 'sha1':
  1111. case 'sha256':
  1112. case 'sha384':
  1113. case 'sha512':
  1114. $this->hash = new Crypt_Hash($hash);
  1115. $this->hashName = $hash;
  1116. break;
  1117. default:
  1118. $this->hash = new Crypt_Hash('sha1');
  1119. $this->hashName = 'sha1';
  1120. }
  1121. $this->hLen = $this->hash->getLength();
  1122. }
  1123. /**
  1124. * Determines which hashing function should be used for the mask generation function
  1125. *
  1126. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1127. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1128. *
  1129. * @access public
  1130. * @param String $hash
  1131. */
  1132. function setMGFHash($hash)
  1133. {
  1134. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1135. switch ($hash) {
  1136. case 'md2':
  1137. case 'md5':
  1138. case 'sha1':
  1139. case 'sha256':
  1140. case 'sha384':
  1141. case 'sha512':
  1142. $this->mgfHash = new Crypt_Hash($hash);
  1143. break;
  1144. default:
  1145. $this->mgfHash = new Crypt_Hash('sha1');
  1146. }
  1147. $this->mgfHLen = $this->mgfHash->getLength();
  1148. }
  1149. /**
  1150. * Determines the salt length
  1151. *
  1152. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1153. *
  1154. * Typical salt lengths in octets are hLen (the length of the output
  1155. * of the hash function Hash) and 0.
  1156. *
  1157. * @access public
  1158. * @param Integer $format
  1159. */
  1160. function setSaltLength($sLen)
  1161. {
  1162. $this->sLen = $sLen;
  1163. }
  1164. /**
  1165. * Generates a random string x bytes long
  1166. *
  1167. * @access public
  1168. * @param Integer $bytes
  1169. * @param optional Integer $nonzero
  1170. * @return String
  1171. */
  1172. function _random($bytes, $nonzero = false)
  1173. {
  1174. $temp = '';
  1175. if ($nonzero) {
  1176. for ($i = 0; $i < $bytes; $i++) {
  1177. $temp.= chr(crypt_random(1, 255));
  1178. }
  1179. } else {
  1180. $ints = ($bytes + 1) >> 2;
  1181. for ($i = 0; $i < $ints; $i++) {
  1182. $temp.= pack('N', crypt_random());
  1183. }
  1184. $temp = substr($temp, 0, $bytes);
  1185. }
  1186. return $temp;
  1187. }
  1188. /**
  1189. * Integer-to-Octet-String primitive
  1190. *
  1191. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1192. *
  1193. * @access private
  1194. * @param Math_BigInteger $x
  1195. * @param Integer $xLen
  1196. * @return String
  1197. */
  1198. function _i2osp($x, $xLen)
  1199. {
  1200. $x = $x->toBytes();
  1201. if (strlen($x) > $xLen) {
  1202. user_error('Integer too large', E_USER_NOTICE);
  1203. return false;
  1204. }
  1205. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1206. }
  1207. /**
  1208. * Octet-String-to-Integer primitive
  1209. *
  1210. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1211. *
  1212. * @access private
  1213. * @param String $x
  1214. * @return Math_BigInteger
  1215. */
  1216. function _os2ip($x)
  1217. {
  1218. return new Math_BigInteger($x, 256);
  1219. }
  1220. /**
  1221. * Exponentiate with or without Chinese Remainder Theorem
  1222. *
  1223. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1224. *
  1225. * @access private
  1226. * @param Math_BigInteger $x
  1227. * @return Math_BigInteger
  1228. */
  1229. function _exponentiate($x)
  1230. {
  1231. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1232. return $x->modPow($this->exponent, $this->modulus);
  1233. }
  1234. $num_primes = count($this->primes);
  1235. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1236. $m_i = array(
  1237. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1238. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1239. );
  1240. $h = $m_i[1]->subtract($m_i[2]);
  1241. $h = $h->multiply($this->coefficients[2]);
  1242. list(, $h) = $h->divide($this->primes[1]);
  1243. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1244. $r = $this->primes[1];
  1245. for ($i = 3; $i <= $num_primes; $i++) {
  1246. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1247. $r = $r->multiply($this->primes[$i - 1]);
  1248. $h = $m_i->subtract($m);
  1249. $h = $h->multiply($this->coefficients[$i]);
  1250. list(, $h) = $h->divide($this->primes[$i]);
  1251. $m = $m->add($r->multiply($h));
  1252. }
  1253. } else {
  1254. $smallest = $this->primes[1];
  1255. for ($i = 2; $i <= $num_primes; $i++) {
  1256. if ($smallest->compare($this->primes[$i]) > 0) {
  1257. $smallest = $this->primes[$i];
  1258. }
  1259. }
  1260. $one = new Math_BigInteger(1);
  1261. $one->setRandomGenerator('crypt_random');
  1262. $r = $one->random($one, $smallest->subtract($one));
  1263. $m_i = array(
  1264. 1 => $this->_blind($x, $r, 1),
  1265. 2 => $this->_blind($x, $r, 2)
  1266. );
  1267. $h = $m_i[1]->subtract($m_i[2]);
  1268. $h = $h->multiply($this->coefficients[2]);
  1269. list(, $h) = $h->divide($this->primes[1]);
  1270. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1271. $r = $this->primes[1];
  1272. for ($i = 3; $i <= $num_primes; $i++) {
  1273. $m_i = $this->_blind($x, $r, $i);
  1274. $r = $r->multiply($this->primes[$i - 1]);
  1275. $h = $m_i->subtract($m);
  1276. $h = $h->multiply($this->coefficients[$i]);
  1277. list(, $h) = $h->divide($this->primes[$i]);
  1278. $m = $m->add($r->multiply($h));
  1279. }
  1280. }
  1281. return $m;
  1282. }
  1283. /**
  1284. * Performs RSA Blinding
  1285. *
  1286. * Protects against timing attacks by employing RSA Blinding.
  1287. * Returns $x->modPow($this->exponents[$i…

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