PageRenderTime 58ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/phpseclib/phpseclib/Crypt/RSA.php

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