PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/davide_grobberio/laravel-angular
PHP | 2988 lines | 1580 code | 294 blank | 1114 comment | 279 complexity | 92986eff3f5014b0ad4f920a7ed1ce11 MD5 | raw file
Possible License(s): 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. // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
  460. // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
  461. // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
  462. if ( defined('MATH_BIGINTEGER_OPENSSL_DISABLE') ) {
  463. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  464. }
  465. switch ( !defined('CRYPT_RSA_MODE') ) { // ie. only run this if the above didn't set CRYPT_RSA_MODE already
  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. case true:
  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. $num_primes = count($primes);
  679. $raw = array(
  680. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  681. 'modulus' => $n->toBytes(true),
  682. 'publicExponent' => $e->toBytes(true),
  683. 'privateExponent' => $d->toBytes(true),
  684. 'prime1' => $primes[1]->toBytes(true),
  685. 'prime2' => $primes[2]->toBytes(true),
  686. 'exponent1' => $exponents[1]->toBytes(true),
  687. 'exponent2' => $exponents[2]->toBytes(true),
  688. 'coefficient' => $coefficients[2]->toBytes(true)
  689. );
  690. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  691. // call _convertPublicKey() instead.
  692. switch ($this->privateKeyFormat) {
  693. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  694. if ($num_primes != 2) {
  695. return false;
  696. }
  697. return "<RSAKeyValue>\r\n" .
  698. ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
  699. ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
  700. ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
  701. ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
  702. ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
  703. ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
  704. ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
  705. ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
  706. '</RSAKeyValue>';
  707. break;
  708. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  709. if ($num_primes != 2) {
  710. return false;
  711. }
  712. $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
  713. $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
  714. $key.= $encryption;
  715. $key.= "\r\nComment: " . $this->comment . "\r\n";
  716. $public = pack('Na*Na*Na*',
  717. strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
  718. );
  719. $source = pack('Na*Na*Na*Na*',
  720. strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
  721. strlen($this->comment), $this->comment, strlen($public), $public
  722. );
  723. $public = base64_encode($public);
  724. $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
  725. $key.= chunk_split($public, 64);
  726. $private = pack('Na*Na*Na*Na*',
  727. strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
  728. strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
  729. );
  730. if (empty($this->password) && !is_string($this->password)) {
  731. $source.= pack('Na*', strlen($private), $private);
  732. $hashkey = 'putty-private-key-file-mac-key';
  733. } else {
  734. $private.= crypt_random_string(16 - (strlen($private) & 15));
  735. $source.= pack('Na*', strlen($private), $private);
  736. if (!class_exists('Crypt_AES')) {
  737. include_once 'Crypt/AES.php';
  738. }
  739. $sequence = 0;
  740. $symkey = '';
  741. while (strlen($symkey) < 32) {
  742. $temp = pack('Na*', $sequence++, $this->password);
  743. $symkey.= pack('H*', sha1($temp));
  744. }
  745. $symkey = substr($symkey, 0, 32);
  746. $crypto = new Crypt_AES();
  747. $crypto->setKey($symkey);
  748. $crypto->disablePadding();
  749. $private = $crypto->encrypt($private);
  750. $hashkey = 'putty-private-key-file-mac-key' . $this->password;
  751. }
  752. $private = base64_encode($private);
  753. $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
  754. $key.= chunk_split($private, 64);
  755. if (!class_exists('Crypt_Hash')) {
  756. include_once 'Crypt/Hash.php';
  757. }
  758. $hash = new Crypt_Hash('sha1');
  759. $hash->setKey(pack('H*', sha1($hashkey)));
  760. $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
  761. return $key;
  762. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  763. $components = array();
  764. foreach ($raw as $name => $value) {
  765. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  766. }
  767. $RSAPrivateKey = implode('', $components);
  768. if ($num_primes > 2) {
  769. $OtherPrimeInfos = '';
  770. for ($i = 3; $i <= $num_primes; $i++) {
  771. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  772. //
  773. // OtherPrimeInfo ::= SEQUENCE {
  774. // prime INTEGER, -- ri
  775. // exponent INTEGER, -- di
  776. // coefficient INTEGER -- ti
  777. // }
  778. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  779. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  780. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  781. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  782. }
  783. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  784. }
  785. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  786. if ($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8) {
  787. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  788. $RSAPrivateKey = pack('Ca*a*Ca*a*',
  789. CRYPT_RSA_ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  790. );
  791. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  792. if (!empty($this->password) || is_string($this->password)) {
  793. $salt = crypt_random_string(8);
  794. $iterationCount = 2048;
  795. if (!class_exists('Crypt_DES')) {
  796. include_once 'Crypt/DES.php';
  797. }
  798. $crypto = new Crypt_DES();
  799. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  800. $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
  801. $parameters = pack('Ca*a*Ca*N',
  802. CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt,
  803. CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(4), $iterationCount
  804. );
  805. $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
  806. $encryptionAlgorithm = pack('Ca*a*Ca*a*',
  807. CRYPT_RSA_ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC,
  808. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters
  809. );
  810. $RSAPrivateKey = pack('Ca*a*Ca*a*',
  811. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm,
  812. CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  813. );
  814. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  815. $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" .
  816. chunk_split(base64_encode($RSAPrivateKey), 64) .
  817. '-----END ENCRYPTED PRIVATE KEY-----';
  818. } else {
  819. $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" .
  820. chunk_split(base64_encode($RSAPrivateKey), 64) .
  821. '-----END PRIVATE KEY-----';
  822. }
  823. return $RSAPrivateKey;
  824. }
  825. if (!empty($this->password) || is_string($this->password)) {
  826. $iv = crypt_random_string(8);
  827. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  828. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  829. if (!class_exists('Crypt_TripleDES')) {
  830. include_once 'Crypt/TripleDES.php';
  831. }
  832. $des = new Crypt_TripleDES();
  833. $des->setKey($symkey);
  834. $des->setIV($iv);
  835. $iv = strtoupper(bin2hex($iv));
  836. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  837. "Proc-Type: 4,ENCRYPTED\r\n" .
  838. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  839. "\r\n" .
  840. chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
  841. '-----END RSA PRIVATE KEY-----';
  842. } else {
  843. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  844. chunk_split(base64_encode($RSAPrivateKey), 64) .
  845. '-----END RSA PRIVATE KEY-----';
  846. }
  847. return $RSAPrivateKey;
  848. }
  849. }
  850. /**
  851. * Convert a public key to the appropriate format
  852. *
  853. * @access private
  854. * @see setPublicKeyFormat()
  855. * @param String $RSAPrivateKey
  856. * @return String
  857. */
  858. function _convertPublicKey($n, $e)
  859. {
  860. $modulus = $n->toBytes(true);
  861. $publicExponent = $e->toBytes(true);
  862. switch ($this->publicKeyFormat) {
  863. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  864. return array('e' => $e->copy(), 'n' => $n->copy());
  865. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  866. return "<RSAKeyValue>\r\n" .
  867. ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
  868. ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
  869. '</RSAKeyValue>';
  870. break;
  871. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  872. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  873. // string "ssh-rsa"
  874. // mpint e
  875. // mpint n
  876. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  877. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
  878. return $RSAPublicKey;
  879. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  880. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  881. // RSAPublicKey ::= SEQUENCE {
  882. // modulus INTEGER, -- n
  883. // publicExponent INTEGER -- e
  884. // }
  885. $components = array(
  886. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  887. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  888. );
  889. $RSAPublicKey = pack('Ca*a*a*',
  890. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  891. $components['modulus'], $components['publicExponent']
  892. );
  893. if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) {
  894. $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
  895. chunk_split(base64_encode($RSAPublicKey), 64) .
  896. '-----END RSA PUBLIC KEY-----';
  897. } else {
  898. // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
  899. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  900. $RSAPublicKey = chr(0) . $RSAPublicKey;
  901. $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  902. $RSAPublicKey = pack('Ca*a*',
  903. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
  904. );
  905. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  906. chunk_split(base64_encode($RSAPublicKey), 64) .
  907. '-----END PUBLIC KEY-----';
  908. }
  909. return $RSAPublicKey;
  910. }
  911. }
  912. /**
  913. * Break a public or private key down into its constituant components
  914. *
  915. * @access private
  916. * @see _convertPublicKey()
  917. * @see _convertPrivateKey()
  918. * @param String $key
  919. * @param Integer $type
  920. * @return Array
  921. */
  922. function _parseKey($key, $type)
  923. {
  924. if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
  925. return false;
  926. }
  927. switch ($type) {
  928. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  929. if (!is_array($key)) {
  930. return false;
  931. }
  932. $components = array();
  933. switch (true) {
  934. case isset($key['e']):
  935. $components['publicExponent'] = $key['e']->copy();
  936. break;
  937. case isset($key['exponent']):
  938. $components['publicExponent'] = $key['exponent']->copy();
  939. break;
  940. case isset($key['publicExponent']):
  941. $components['publicExponent'] = $key['publicExponent']->copy();
  942. break;
  943. case isset($key[0]):
  944. $components['publicExponent'] = $key[0]->copy();
  945. }
  946. switch (true) {
  947. case isset($key['n']):
  948. $components['modulus'] = $key['n']->copy();
  949. break;
  950. case isset($key['modulo']):
  951. $components['modulus'] = $key['modulo']->copy();
  952. break;
  953. case isset($key['modulus']):
  954. $components['modulus'] = $key['modulus']->copy();
  955. break;
  956. case isset($key[1]):
  957. $components['modulus'] = $key[1]->copy();
  958. }
  959. return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
  960. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  961. case CRYPT_RSA_PRIVATE_FORMAT_PKCS8:
  962. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  963. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  964. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  965. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  966. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  967. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  968. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  969. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  970. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  971. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  972. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  973. implementation are part of the standard, as well.
  974. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  975. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  976. $iv = pack('H*', trim($matches[2]));
  977. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  978. $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
  979. // remove the Proc-Type / DEK-Info sections as they're no longer needed
  980. $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
  981. $ciphertext = $this->_extractBER($key);
  982. if ($ciphertext === false) {
  983. $ciphertext = $key;
  984. }
  985. switch ($matches[1]) {
  986. case 'AES-256-CBC':
  987. if (!class_exists('Crypt_AES')) {
  988. include_once 'Crypt/AES.php';
  989. }
  990. $crypto = new Crypt_AES();
  991. break;
  992. case 'AES-128-CBC':
  993. if (!class_exists('Crypt_AES')) {
  994. include_once 'Crypt/AES.php';
  995. }
  996. $symkey = substr($symkey, 0, 16);
  997. $crypto = new Crypt_AES();
  998. break;
  999. case 'DES-EDE3-CFB':
  1000. if (!class_exists('Crypt_TripleDES')) {
  1001. include_once 'Crypt/TripleDES.php';
  1002. }
  1003. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  1004. break;
  1005. case 'DES-EDE3-CBC':
  1006. if (!class_exists('Crypt_TripleDES')) {
  1007. include_once 'Crypt/TripleDES.php';
  1008. }
  1009. $symkey = substr($symkey, 0, 24);
  1010. $crypto = new Crypt_TripleDES();
  1011. break;
  1012. case 'DES-CBC':
  1013. if (!class_exists('Crypt_DES')) {
  1014. include_once 'Crypt/DES.php';
  1015. }
  1016. $crypto = new Crypt_DES();
  1017. break;
  1018. default:
  1019. return false;
  1020. }
  1021. $crypto->setKey($symkey);
  1022. $crypto->setIV($iv);
  1023. $decoded = $crypto->decrypt($ciphertext);
  1024. } else {
  1025. $decoded = $this->_extractBER($key);
  1026. }
  1027. if ($decoded !== false) {
  1028. $key = $decoded;
  1029. }
  1030. $components = array();
  1031. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1032. return false;
  1033. }
  1034. if ($this->_decodeLength($key) != strlen($key)) {
  1035. return false;
  1036. }
  1037. $tag = ord($this->_string_shift($key));
  1038. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1039. 0:d=0 hl=4 l= 631 cons: SEQUENCE
  1040. 4:d=1 hl=2 l= 1 prim: INTEGER :00
  1041. 7:d=1 hl=2 l= 13 cons: SEQUENCE
  1042. 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1043. 20:d=2 hl=2 l= 0 prim: NULL
  1044. 22:d=1 hl=4 l= 609 prim: OCTET STRING
  1045. ie. PKCS8 keys*/
  1046. if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
  1047. $this->_string_shift($key, 3);
  1048. $tag = CRYPT_RSA_ASN1_SEQUENCE;
  1049. }
  1050. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  1051. $temp = $this->_string_shift($key, $this->_decodeLength($key));
  1052. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT) {
  1053. return false;
  1054. }
  1055. $length = $this->_decodeLength($temp);
  1056. switch ($this->_string_shift($temp, $length)) {
  1057. case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption
  1058. break;
  1059. case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC
  1060. /*
  1061. PBEParameter ::= SEQUENCE {
  1062. salt OCTET STRING (SIZE(8)),
  1063. iterationCount INTEGER }
  1064. */
  1065. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1066. return false;
  1067. }
  1068. if ($this->_decodeLength($temp) != strlen($temp)) {
  1069. return false;
  1070. }
  1071. $this->_string_shift($temp); // assume it's an octet string
  1072. $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
  1073. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER) {
  1074. return false;
  1075. }
  1076. $this->_decodeLength($temp);
  1077. list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
  1078. $this->_string_shift($key); // assume it's an octet string
  1079. $length = $this->_decodeLength($key);
  1080. if (strlen($key) != $length) {
  1081. return false;
  1082. }
  1083. if (!class_exists('Crypt_DES')) {
  1084. include_once 'Crypt/DES.php';
  1085. }
  1086. $crypto = new Crypt_DES();
  1087. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  1088. $key = $crypto->decrypt($key);
  1089. if ($key === false) {
  1090. return false;
  1091. }
  1092. return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
  1093. default:
  1094. return false;
  1095. }
  1096. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1097. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  1098. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  1099. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1100. 17:d=2 hl=2 l= 0 prim: NULL
  1101. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  1102. $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
  1103. $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
  1104. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  1105. // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
  1106. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  1107. if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
  1108. $this->_string_shift($key);
  1109. }
  1110. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1111. return false;
  1112. }
  1113. if ($this->_decodeLength($key) != strlen($key)) {
  1114. return false;
  1115. }
  1116. $tag = ord($this->_string_shift($key));
  1117. }
  1118. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  1119. return false;
  1120. }
  1121. $length = $this->_decodeLength($key);
  1122. $temp = $this->_string_shift($key, $length);
  1123. if (strlen($temp) != 1 || ord($temp) > 2) {
  1124. $components['modulus'] = new Math_BigInteger($temp, 256);
  1125. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  1126. $length = $this->_decodeLength($key);
  1127. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1128. return $components;
  1129. }
  1130. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  1131. return false;
  1132. }
  1133. $length = $this->_decodeLength($key);
  1134. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1135. $this->_string_shift($key);
  1136. $length = $this->_decodeLength($key);
  1137. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1138. $this->_string_shift($key);
  1139. $length = $this->_decodeLength($key);
  1140. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1141. $this->_string_shift($key);
  1142. $length = $this->_decodeLength($key);
  1143. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1144. $this->_string_shift($key);
  1145. $length = $this->_decodeLength($key);
  1146. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1147. $this->_string_shift($key);
  1148. $length = $this->_decodeLength($key);
  1149. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1150. $this->_string_shift($key);
  1151. $length = $this->_decodeLength($key);
  1152. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1153. $this->_string_shift($key);
  1154. $length = $this->_decodeLength($key);
  1155. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1156. if (!empty($key)) {
  1157. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1158. return false;
  1159. }
  1160. $this->_decodeLength($key);
  1161. while (!empty($key)) {
  1162. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1163. return false;
  1164. }
  1165. $this->_decodeLength($key);
  1166. $key = substr($key, 1);
  1167. $length = $this->_decodeLength($key);
  1168. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1169. $this->_string_shift($key);
  1170. $length = $this->_decodeLength($key);
  1171. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1172. $this->_string_shift($key);
  1173. $length = $this->_decodeLength($key);
  1174. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1175. }
  1176. }
  1177. return $components;
  1178. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  1179. $parts = explode(' ', $key, 3);
  1180. $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
  1181. if ($key === false) {
  1182. return false;
  1183. }
  1184. $comment = isset($parts[2]) ? $parts[2] : false;
  1185. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  1186. if (strlen($key) <= 4) {
  1187. return false;
  1188. }
  1189. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1190. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1191. if (strlen($key) <= 4) {
  1192. return false;
  1193. }
  1194. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1195. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1196. if ($cleanup && strlen($key)) {
  1197. if (strlen($key) <= 4) {
  1198. return false;
  1199. }
  1200. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1201. $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  1202. return strlen($key) ? false : array(
  1203. 'modulus' => $realModulus,
  1204. 'publicExponent' => $modulus,
  1205. 'comment' => $comment
  1206. );
  1207. } else {
  1208. return strlen($key) ? false : array(
  1209. 'modulus' => $modulus,
  1210. 'publicExponent' => $publicExponent,
  1211. 'comment' => $comment
  1212. );
  1213. }
  1214. // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
  1215. // http://en.wikipedia.org/wiki/XML_Signature
  1216. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  1217. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  1218. $this->components = array();
  1219. $xml = xml_parser_create('UTF-8');
  1220. xml_set_object($xml, $this);
  1221. xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
  1222. xml_set_character_data_handler($xml, '_data_handler');
  1223. // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
  1224. if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
  1225. return false;
  1226. }
  1227. return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
  1228. // from PuTTY's SSHPUBK.C
  1229. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  1230. $components = array();
  1231. $key = preg_split('#\r\n|\r|\n#', $key);
  1232. $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
  1233. if ($type != 'ssh-rsa') {
  1234. return false;
  1235. }
  1236. $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
  1237. $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
  1238. $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
  1239. $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
  1240. $public = substr($public, 11);
  1241. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1242. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  1243. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1244. $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  1245. $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
  1246. $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
  1247. switch ($encryption) {
  1248. case 'aes256-cbc':
  1249. if (!class_exists('Crypt_AES')) {
  1250. include_once 'Crypt/AES.php';
  1251. }
  1252. $symkey = '';
  1253. $sequence = 0;
  1254. while (strlen($symkey) < 32) {
  1255. $temp = pack('Na*', $sequence++, $this->password);
  1256. $symkey.= pack('H*', sha1($temp));
  1257. }
  1258. $symkey = substr($symkey, 0, 32);
  1259. $crypto = new Crypt_AES();
  1260. }
  1261. if ($encryption != 'none') {
  1262. $crypto->setKey($symkey);
  1263. $crypto->disablePadding();
  1264. $private = $crypto->decrypt($private);
  1265. if ($private === false) {
  1266. return false;
  1267. }
  1268. }
  1269. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1270. if (strlen($private) < $length) {
  1271. return false;
  1272. }
  1273. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  1274. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1275. if (strlen($private) < $length) {
  1276. return false;
  1277. }
  1278. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  1279. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1280. if (strlen($private) < $length) {
  1281. return false;
  1282. }
  1283. $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  1284. $temp = $components['primes'][1]->subtract($this->one);
  1285. $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
  1286. $temp = $components['primes'][2]->subtract($this->one);
  1287. $components['exponents'][] = $components['publicExponent']->modInverse($temp);
  1288. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1289. if (strlen($private) < $length) {
  1290. return false;
  1291. }
  1292. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  1293. return $components;
  1294. }
  1295. }
  1296. /**
  1297. * Returns the key size
  1298. *
  1299. * More specifically, this returns the size of the modulo in bits.
  1300. *
  1301. * @access public
  1302. * @return Integer
  1303. */
  1304. function getSize()
  1305. {
  1306. return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
  1307. }
  1308. /**
  1309. * Start Element Handler
  1310. *
  1311. * Called by xml_set_element_handler()
  1312. *
  1313. * @access private
  1314. * @param Resource $parser
  1315. * @param String $name
  1316. * @param Array $attribs
  1317. */
  1318. function _start_element_handler($parser, $name, $attribs)
  1319. {
  1320. //$name = strtoupper($name);
  1321. switch ($name) {
  1322. case 'MODULUS':
  1323. $this->current = &$this->components['modulus'];
  1324. break;
  1325. case 'EXPONENT':
  1326. $this->current = &$this->components['publicExponent'];
  1327. break;
  1328. case 'P':
  1329. $this->current = &$this->components['primes'][1];
  1330. break;
  1331. case 'Q':
  1332. $this->current = &$this->components['primes'][2];
  1333. break;
  1334. case 'DP':
  1335. $this->current = &$this->components['exponents'][1];
  1336. break;
  1337. case 'DQ':
  1338. $this->current = &$this->components['exponents'][2];
  1339. break;
  1340. case 'INVERSEQ':
  1341. $this->current = &$this->components['coefficients'][2];
  1342. break;
  1343. case 'D':
  1344. $this->current = &$this->components['privateExponent'];
  1345. }
  1346. $this->current = '';
  1347. }
  1348. /**
  1349. * Stop Element Handler
  1350. *
  1351. * Called by xml_set_element_handler()
  1352. *
  1353. * @access private
  1354. * @param Resource $parser
  1355. * @param String $name
  1356. */
  1357. function _stop_element_handler($parser, $name)
  1358. {
  1359. if (isset($this->current)) {
  1360. $this->current = new Math_BigInteger(base64_decode($this->current), 256);
  1361. unset($this->current);
  1362. }
  1363. }
  1364. /**
  1365. * Data Handler
  1366. *
  1367. * Called by xml_set_character_data_handler()
  1368. *
  1369. * @access private
  1370. * @param Resource $parser
  1371. * @param String $data
  1372. */
  1373. function _data_handler($parser, $data)
  1374. {
  1375. if (!isset($this->current) || is_object($this->current)) {
  1376. return;
  1377. }
  1378. $this->current.= trim($data);
  1379. }
  1380. /**
  1381. * Loads a public or private key
  1382. *
  1383. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  1384. *
  1385. * @access public
  1386. * @param String $key
  1387. * @param Integer $type optional
  1388. */
  1389. function loadKey($key, $type = false)
  1390. {
  1391. if (is_object($key) && strtolower(get_class($key)) == 'crypt_rsa') {
  1392. $this->privateKeyFormat = $key->privateKeyFormat;
  1393. $this->publicKeyFormat = $key->publicKeyFormat;
  1394. $this->k = $key->k;
  1395. $this->hLen = $key->hLen;
  1396. $this->sLen = $key->sLen;
  1397. $this->mgfHLen = $key->mgfHLen;
  1398. $this->encryptionMode = $key->encryptionMode;
  1399. $this->signatureMode = $key->signatureMode;
  1400. $this->password = $key->password;
  1401. $this->configFile = $key->configFile;
  1402. $this->comment = $key->comment;
  1403. if (is_object($key->hash)) {
  1404. $this->hash = new Crypt_Hash($key->hash->getHash());
  1405. }
  1406. if (is_object($key->mgfHash)) {
  1407. $this->mgfHash = new Crypt_Hash($key->mgfHash->getHash());
  1408. }
  1409. if (is_object($key->modulus)) {
  1410. $this->modulus = $key->modulus->copy();
  1411. }
  1412. if (is_object($key->exponent)) {
  1413. $this->exponent = $key->exponent->copy();
  1414. }
  1415. if (is_object($key->publicExponent)) {
  1416. $this->publicExponent = $key->publicExponent->copy();
  1417. }
  1418. $this->primes = array();
  1419. $this->exponents = array();
  1420. $this->coefficients = array();
  1421. foreach ($this->primes as $prime) {
  1422. $this->primes[] = $prime->copy();
  1423. }
  1424. foreach ($this->exponents as $exponent) {
  1425. $this->exponents[] = $exponent->copy();
  1426. }
  1427. foreach ($this->coefficients as $coefficient) {
  1428. $this->coefficients[] = $coefficient->copy();
  1429. }
  1430. return true;
  1431. }
  1432. if ($type === false) {
  1433. $types = array(
  1434. CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1435. CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
  1436. CRYPT_RSA_PRIVATE_FORMAT_XML,
  1437. CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
  1438. CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1439. );
  1440. foreach ($types as $type) {
  1441. $components = $this->_parseKey($key, $type);
  1442. if ($components !== false) {
  1443. break;
  1444. }
  1445. }
  1446. } else {
  1447. $components = $this->_parseKey($key, $type);
  1448. }
  1449. if ($components === false) {
  1450. return false;
  1451. }
  1452. if (isset($components['comment']) && $components['comment'] !== false) {
  1453. $this->comment = $components['comment'];
  1454. }
  1455. $this->modulus = $components['modulus'];
  1456. $this->k = strlen($this->modulus->toBytes());
  1457. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  1458. if (isset($components['primes'])) {
  1459. $this->primes = $components['primes'];
  1460. $this->exponents = $components['exponents'];
  1461. $this->coefficients = $components['coefficients'];
  1462. $this->publicExponent = $components['publicExponent'];
  1463. } else {
  1464. $this->primes = array();
  1465. $this->exponents = array();
  1466. $this->coefficients = array();
  1467. $this->publicExponent = false;
  1468. }
  1469. switch ($type) {
  1470. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  1471. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  1472. $this->setPublicKey();
  1473. break;
  1474. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  1475. switch (true) {
  1476. case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
  1477. case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
  1478. $this->setPublicKey();
  1479. }
  1480. }
  1481. return true;
  1482. }
  1483. /**
  1484. * Sets the password
  1485. *
  1486. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  1487. * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  1488. *
  1489. * @see createKey()
  1490. * @see loadKey()
  1491. * @access public
  1492. * @param String $password
  1493. */
  1494. function setPassword($password = false)
  1495. {
  1496. $this->password = $password;
  1497. }
  1498. /**
  1499. * Defines the public key
  1500. *
  1501. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  1502. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  1503. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  1504. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  1505. * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used
  1506. * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being
  1507. * public.
  1508. *
  1509. * Do note that when a new key is loaded the index will be cleared.
  1510. *
  1511. * Returns true on success, false on failure
  1512. *
  1513. * @see getPublicKey()
  1514. * @access public
  1515. * @param String $key optional
  1516. * @param Integer $type optional
  1517. * @return Boolean
  1518. */
  1519. function setPublicKey($key = false, $type = false)
  1520. {
  1521. // if a public key has already been loaded return false
  1522. if (!empty($this->publicExponent)) {
  1523. return false;
  1524. }
  1525. if ($key === false && !empty($this->modulus)) {
  1526. $this->publicExponent = $this->exponent;
  1527. return true;
  1528. }
  1529. if ($type === false) {
  1530. $types = array(
  1531. CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1532. CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
  1533. CRYPT_RSA_PUBLIC_FORMAT_XML,
  1534. CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1535. );
  1536. foreach ($types as $type) {
  1537. $components = $this->_parseKey($key, $type);
  1538. if ($components !== false) {
  1539. break;
  1540. }
  1541. }
  1542. } else {
  1543. $components = $this->_parseKey($key, $type);
  1544. }
  1545. if ($components === false) {
  1546. return false;
  1547. }
  1548. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  1549. $this->modulus = $components['modulus'];
  1550. $this->exponent = $this->publicExponent = $components['publicExponent'];
  1551. return true;
  1552. }
  1553. $this->publicExponent = $components['publicExponent'];
  1554. return true;
  1555. }
  1556. /**
  1557. * Defines the private key
  1558. *
  1559. * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force
  1560. * phpseclib to treat the key as a private key. This function will do that.
  1561. *
  1562. * Do note that when a new key is loaded the index will be cleared.
  1563. *
  1564. * Returns true on success, false on failure
  1565. *
  1566. * @see getPublicKey()
  1567. * @access public
  1568. * @param String $key optional
  1569. * @param Integer $type optional
  1570. * @return Boolean
  1571. */
  1572. function setPrivateKey($key = false, $type = false)
  1573. {
  1574. if ($key === false && !empty($this->publicExponent)) {
  1575. unset($this->publicExponent);
  1576. return true;
  1577. }
  1578. $rsa = new Crypt_RSA();
  1579. if (!$rsa->loadKey($key, $type)) {
  1580. return false;
  1581. }
  1582. unset($rsa->publicExponent);
  1583. // don't overwrite the old key if the new key is invalid
  1584. $this->loadKey($rsa);
  1585. return true;
  1586. }
  1587. /**
  1588. * Returns the public key
  1589. *
  1590. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  1591. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  1592. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  1593. *
  1594. * @see getPublicKey()
  1595. * @access public
  1596. * @param String $key
  1597. * @param Integer $type optional
  1598. */
  1599. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)
  1600. {
  1601. if (empty($this->modulus) || empty($this->publicExponent)) {
  1602. return false;
  1603. }
  1604. $oldFormat = $this->publicKeyFormat;
  1605. $this->publicKeyFormat = $type;
  1606. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  1607. $this->publicKeyFormat = $oldFormat;
  1608. return $temp;
  1609. }
  1610. /**
  1611. * Returns the private key
  1612. *
  1613. * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  1614. *
  1615. * @see getPublicKey()
  1616. * @access public
  1617. * @param String $key
  1618. * @param Integer $type optional
  1619. */
  1620. function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1621. {
  1622. if (empty($this->primes)) {
  1623. return false;
  1624. }
  1625. $oldFormat = $this->privateKeyFormat;
  1626. $this->privateKeyFormat = $type;
  1627. $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
  1628. $this->privateKeyFormat = $oldFormat;
  1629. return $temp;
  1630. }
  1631. /**
  1632. * Returns a minimalistic private key
  1633. *
  1634. * Returns the private key without the prime number constituants. Structurally identical to a public key that
  1635. * hasn't been set as the public key
  1636. *
  1637. * @see getPrivateKey()
  1638. * @access private
  1639. * @param String $key
  1640. * @param Integer $type optional
  1641. */
  1642. function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8)
  1643. {
  1644. if (empty($this->modulus) || empty($this->exponent)) {
  1645. return false;
  1646. }
  1647. $oldFormat = $this->publicKeyFormat;
  1648. $this->publicKeyFormat = $mode;
  1649. $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
  1650. $this->publicKeyFormat = $oldFormat;
  1651. return $temp;
  1652. }
  1653. /**
  1654. * __toString() magic method
  1655. *
  1656. * @access public
  1657. */
  1658. function __toString()
  1659. {
  1660. $key = $this->getPrivateKey($this->privateKeyFormat);
  1661. if ($key !== false) {
  1662. return $key;
  1663. }
  1664. $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
  1665. return $key !== false ? $key : '';
  1666. }
  1667. /**
  1668. * __clone() magic method
  1669. *
  1670. * @access public
  1671. */
  1672. function __clone()
  1673. {
  1674. $key = new Crypt_RSA();
  1675. $key->loadKey($this);
  1676. return $key;
  1677. }
  1678. /**
  1679. * Generates the smallest and largest numbers requiring $bits bits
  1680. *
  1681. * @access private
  1682. * @param Integer $bits
  1683. * @return Array
  1684. */
  1685. function _generateMinMax($bits)
  1686. {
  1687. $bytes = $bits >> 3;
  1688. $min = str_repeat(chr(0), $bytes);
  1689. $max = str_repeat(chr(0xFF), $bytes);
  1690. $msb = $bits & 7;
  1691. if ($msb) {
  1692. $min = chr(1 << ($msb - 1)) . $min;
  1693. $max = chr((1 << $msb) - 1) . $max;
  1694. } else {
  1695. $min[0] = chr(0x80);
  1696. }
  1697. return array(
  1698. 'min' => new Math_BigInteger($min, 256),
  1699. 'max' => new Math_BigInteger($max, 256)
  1700. );
  1701. }
  1702. /**
  1703. * DER-decode the length
  1704. *
  1705. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1706. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1707. *
  1708. * @access private
  1709. * @param String $string
  1710. * @return Integer
  1711. */
  1712. function _decodeLength(&$string)
  1713. {
  1714. $length = ord($this->_string_shift($string));
  1715. if ( $length & 0x80 ) { // definite length, long form
  1716. $length&= 0x7F;
  1717. $temp = $this->_string_shift($string, $length);
  1718. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1719. }
  1720. return $length;
  1721. }
  1722. /**
  1723. * DER-encode the length
  1724. *
  1725. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1726. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1727. *
  1728. * @access private
  1729. * @param Integer $length
  1730. * @return String
  1731. */
  1732. function _encodeLength($length)
  1733. {
  1734. if ($length <= 0x7F) {
  1735. return chr($length);
  1736. }
  1737. $temp = ltrim(pack('N', $length), chr(0));
  1738. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1739. }
  1740. /**
  1741. * String Shift
  1742. *
  1743. * Inspired by array_shift
  1744. *
  1745. * @param String $string
  1746. * @param optional Integer $index
  1747. * @return String
  1748. * @access private
  1749. */
  1750. function _string_shift(&$string, $index = 1)
  1751. {
  1752. $substr = substr($string, 0, $index);
  1753. $string = substr($string, $index);
  1754. return $substr;
  1755. }
  1756. /**
  1757. * Determines the private key format
  1758. *
  1759. * @see createKey()
  1760. * @access public
  1761. * @param Integer $format
  1762. */
  1763. function setPrivateKeyFormat($format)
  1764. {
  1765. $this->privateKeyFormat = $format;
  1766. }
  1767. /**
  1768. * Determines the public key format
  1769. *
  1770. * @see createKey()
  1771. * @access public
  1772. * @param Integer $format
  1773. */
  1774. function setPublicKeyFormat($format)
  1775. {
  1776. $this->publicKeyFormat = $format;
  1777. }
  1778. /**
  1779. * Determines which hashing function should be used
  1780. *
  1781. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1782. * decryption. If $hash isn't supported, sha1 is used.
  1783. *
  1784. * @access public
  1785. * @param String $hash
  1786. */
  1787. function setHash($hash)
  1788. {
  1789. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1790. switch ($hash) {
  1791. case 'md2':
  1792. case 'md5':
  1793. case 'sha1':
  1794. case 'sha256':
  1795. case 'sha384':
  1796. case 'sha512':
  1797. $this->hash = new Crypt_Hash($hash);
  1798. $this->hashName = $hash;
  1799. break;
  1800. default:
  1801. $this->hash = new Crypt_Hash('sha1');
  1802. $this->hashName = 'sha1';
  1803. }
  1804. $this->hLen = $this->hash->getLength();
  1805. }
  1806. /**
  1807. * Determines which hashing function should be used for the mask generation function
  1808. *
  1809. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1810. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1811. *
  1812. * @access public
  1813. * @param String $hash
  1814. */
  1815. function setMGFHash($hash)
  1816. {
  1817. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1818. switch ($hash) {
  1819. case 'md2':
  1820. case 'md5':
  1821. case 'sha1':
  1822. case 'sha256':
  1823. case 'sha384':
  1824. case 'sha512':
  1825. $this->mgfHash = new Crypt_Hash($hash);
  1826. break;
  1827. default:
  1828. $this->mgfHash = new Crypt_Hash('sha1');
  1829. }
  1830. $this->mgfHLen = $this->mgfHash->getLength();
  1831. }
  1832. /**
  1833. * Determines the salt length
  1834. *
  1835. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1836. *
  1837. * Typical salt lengths in octets are hLen (the length of the output
  1838. * of the hash function Hash) and 0.
  1839. *
  1840. * @access public
  1841. * @param Integer $format
  1842. */
  1843. function setSaltLength($sLen)
  1844. {
  1845. $this->sLen = $sLen;
  1846. }
  1847. /**
  1848. * Integer-to-Octet-String primitive
  1849. *
  1850. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1851. *
  1852. * @access private
  1853. * @param Math_BigInteger $x
  1854. * @param Integer $xLen
  1855. * @return String
  1856. */
  1857. function _i2osp($x, $xLen)
  1858. {
  1859. $x = $x->toBytes();
  1860. if (strlen($x) > $xLen) {
  1861. user_error('Integer too large');
  1862. return false;
  1863. }
  1864. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1865. }
  1866. /**
  1867. * Octet-String-to-Integer primitive
  1868. *
  1869. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1870. *
  1871. * @access private
  1872. * @param String $x
  1873. * @return Math_BigInteger
  1874. */
  1875. function _os2ip($x)
  1876. {
  1877. return new Math_BigInteger($x, 256);
  1878. }
  1879. /**
  1880. * Exponentiate with or without Chinese Remainder Theorem
  1881. *
  1882. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1883. *
  1884. * @access private
  1885. * @param Math_BigInteger $x
  1886. * @return Math_BigInteger
  1887. */
  1888. function _exponentiate($x)
  1889. {
  1890. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1891. return $x->modPow($this->exponent, $this->modulus);
  1892. }
  1893. $num_primes = count($this->primes);
  1894. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1895. $m_i = array(
  1896. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1897. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1898. );
  1899. $h = $m_i[1]->subtract($m_i[2]);
  1900. $h = $h->multiply($this->coefficients[2]);
  1901. list(, $h) = $h->divide($this->primes[1]);
  1902. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1903. $r = $this->primes[1];
  1904. for ($i = 3; $i <= $num_primes; $i++) {
  1905. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1906. $r = $r->multiply($this->primes[$i - 1]);
  1907. $h = $m_i->subtract($m);
  1908. $h = $h->multiply($this->coefficients[$i]);
  1909. list(, $h) = $h->divide($this->primes[$i]);
  1910. $m = $m->add($r->multiply($h));
  1911. }
  1912. } else {
  1913. $smallest = $this->primes[1];
  1914. for ($i = 2; $i <= $num_primes; $i++) {
  1915. if ($smallest->compare($this->primes[$i]) > 0) {
  1916. $smallest = $this->primes[$i];
  1917. }
  1918. }
  1919. $one = new Math_BigInteger(1);
  1920. $r = $one->random($one, $smallest->subtract($one));
  1921. $m_i = array(
  1922. 1 => $this->_blind($x, $r, 1),
  1923. 2 => $this->_blind($x, $r, 2)
  1924. );
  1925. $h = $m_i[1]->subtract($m_i[2]);
  1926. $h = $h->multiply($this->coefficients[2]);
  1927. list(, $h) = $h->divide($this->primes[1]);
  1928. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1929. $r = $this->primes[1];
  1930. for ($i = 3; $i <= $num_primes; $i++) {
  1931. $m_i = $this->_blind($x, $r, $i);
  1932. $r = $r->multiply($this->primes[$i - 1]);
  1933. $h = $m_i->subtract($m);
  1934. $h = $h->multiply($this->coefficients[$i]);
  1935. list(, $h) = $h->divide($this->primes[$i]);
  1936. $m = $m->add($r->multiply($h));
  1937. }
  1938. }
  1939. return $m;
  1940. }
  1941. /**
  1942. * Performs RSA Blinding
  1943. *
  1944. * Protects against timing attacks by employing RSA Blinding.
  1945. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1946. *
  1947. * @access private
  1948. * @param Math_BigInteger $x
  1949. * @param Math_BigInteger $r
  1950. * @param Integer $i
  1951. * @return Math_BigInteger
  1952. */
  1953. function _blind($x, $r, $i)
  1954. {
  1955. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1956. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1957. $r = $r->modInverse($this->primes[$i]);
  1958. $x = $x->multiply($r);
  1959. list(, $x) = $x->divide($this->primes[$i]);
  1960. return $x;
  1961. }
  1962. /**
  1963. * Performs blinded RSA equality testing
  1964. *
  1965. * Protects against a particular type of timing attack described.
  1966. *
  1967. * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
  1968. *
  1969. * Thanks for the heads up singpolyma!
  1970. *
  1971. * @access private
  1972. * @param String $x
  1973. * @param String $y
  1974. * @return Boolean
  1975. */
  1976. function _equals($x, $y)
  1977. {
  1978. if (strlen($x) != strlen($y)) {
  1979. return false;
  1980. }
  1981. $result = 0;
  1982. for ($i = 0; $i < strlen($x); $i++) {
  1983. $result |= ord($x[$i]) ^ ord($y[$i]);
  1984. }
  1985. return $result == 0;
  1986. }
  1987. /**
  1988. * RSAEP
  1989. *
  1990. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1991. *
  1992. * @access private
  1993. * @param Math_BigInteger $m
  1994. * @return Math_BigInteger
  1995. */
  1996. function _rsaep($m)
  1997. {
  1998. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  1999. user_error('Message representative out of range');
  2000. return false;
  2001. }
  2002. return $this->_exponentiate($m);
  2003. }
  2004. /**
  2005. * RSADP
  2006. *
  2007. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  2008. *
  2009. * @access private
  2010. * @param Math_BigInteger $c
  2011. * @return Math_BigInteger
  2012. */
  2013. function _rsadp($c)
  2014. {
  2015. if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
  2016. user_error('Ciphertext representative out of range');
  2017. return false;
  2018. }
  2019. return $this->_exponentiate($c);
  2020. }
  2021. /**
  2022. * RSASP1
  2023. *
  2024. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  2025. *
  2026. * @access private
  2027. * @param Math_BigInteger $m
  2028. * @return Math_BigInteger
  2029. */
  2030. function _rsasp1($m)
  2031. {
  2032. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  2033. user_error('Message representative out of range');
  2034. return false;
  2035. }
  2036. return $this->_exponentiate($m);
  2037. }
  2038. /**
  2039. * RSAVP1
  2040. *
  2041. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  2042. *
  2043. * @access private
  2044. * @param Math_BigInteger $s
  2045. * @return Math_BigInteger
  2046. */
  2047. function _rsavp1($s)
  2048. {
  2049. if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
  2050. user_error('Signature representative out of range');
  2051. return false;
  2052. }
  2053. return $this->_exponentiate($s);
  2054. }
  2055. /**
  2056. * MGF1
  2057. *
  2058. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  2059. *
  2060. * @access private
  2061. * @param String $mgfSeed
  2062. * @param Integer $mgfLen
  2063. * @return String
  2064. */
  2065. function _mgf1($mgfSeed, $maskLen)
  2066. {
  2067. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  2068. $t = '';
  2069. $count = ceil($maskLen / $this->mgfHLen);
  2070. for ($i = 0; $i < $count; $i++) {
  2071. $c = pack('N', $i);
  2072. $t.= $this->mgfHash->hash($mgfSeed . $c);
  2073. }
  2074. return substr($t, 0, $maskLen);
  2075. }
  2076. /**
  2077. * RSAES-OAEP-ENCRYPT
  2078. *
  2079. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  2080. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  2081. *
  2082. * @access private
  2083. * @param String $m
  2084. * @param String $l
  2085. * @return String
  2086. */
  2087. function _rsaes_oaep_encrypt($m, $l = '')
  2088. {
  2089. $mLen = strlen($m);
  2090. // Length checking
  2091. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2092. // be output.
  2093. if ($mLen > $this->k - 2 * $this->hLen - 2) {
  2094. user_error('Message too long');
  2095. return false;
  2096. }
  2097. // EME-OAEP encoding
  2098. $lHash = $this->hash->hash($l);
  2099. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  2100. $db = $lHash . $ps . chr(1) . $m;
  2101. $seed = crypt_random_string($this->hLen);
  2102. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2103. $maskedDB = $db ^ $dbMask;
  2104. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2105. $maskedSeed = $seed ^ $seedMask;
  2106. $em = chr(0) . $maskedSeed . $maskedDB;
  2107. // RSA encryption
  2108. $m = $this->_os2ip($em);
  2109. $c = $this->_rsaep($m);
  2110. $c = $this->_i2osp($c, $this->k);
  2111. // Output the ciphertext C
  2112. return $c;
  2113. }
  2114. /**
  2115. * RSAES-OAEP-DECRYPT
  2116. *
  2117. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  2118. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  2119. *
  2120. * Note. Care must be taken to ensure that an opponent cannot
  2121. * distinguish the different error conditions in Step 3.g, whether by
  2122. * error message or timing, or, more generally, learn partial
  2123. * information about the encoded message EM. Otherwise an opponent may
  2124. * be able to obtain useful information about the decryption of the
  2125. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  2126. * observed by Manger [36].
  2127. *
  2128. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  2129. *
  2130. * Both the encryption and the decryption operations of RSAES-OAEP take
  2131. * the value of a label L as input. In this version of PKCS #1, L is
  2132. * the empty string; other uses of the label are outside the scope of
  2133. * this document.
  2134. *
  2135. * @access private
  2136. * @param String $c
  2137. * @param String $l
  2138. * @return String
  2139. */
  2140. function _rsaes_oaep_decrypt($c, $l = '')
  2141. {
  2142. // Length checking
  2143. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2144. // be output.
  2145. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  2146. user_error('Decryption error');
  2147. return false;
  2148. }
  2149. // RSA decryption
  2150. $c = $this->_os2ip($c);
  2151. $m = $this->_rsadp($c);
  2152. if ($m === false) {
  2153. user_error('Decryption error');
  2154. return false;
  2155. }
  2156. $em = $this->_i2osp($m, $this->k);
  2157. // EME-OAEP decoding
  2158. $lHash = $this->hash->hash($l);
  2159. $y = ord($em[0]);
  2160. $maskedSeed = substr($em, 1, $this->hLen);
  2161. $maskedDB = substr($em, $this->hLen + 1);
  2162. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2163. $seed = $maskedSeed ^ $seedMask;
  2164. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2165. $db = $maskedDB ^ $dbMask;
  2166. $lHash2 = substr($db, 0, $this->hLen);
  2167. $m = substr($db, $this->hLen);
  2168. if ($lHash != $lHash2) {
  2169. user_error('Decryption error');
  2170. return false;
  2171. }
  2172. $m = ltrim($m, chr(0));
  2173. if (ord($m[0]) != 1) {
  2174. user_error('Decryption error');
  2175. return false;
  2176. }
  2177. // Output the message M
  2178. return substr($m, 1);
  2179. }
  2180. /**
  2181. * RSAES-PKCS1-V1_5-ENCRYPT
  2182. *
  2183. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  2184. *
  2185. * @access private
  2186. * @param String $m
  2187. * @return String
  2188. */
  2189. function _rsaes_pkcs1_v1_5_encrypt($m)
  2190. {
  2191. $mLen = strlen($m);
  2192. // Length checking
  2193. if ($mLen > $this->k - 11) {
  2194. user_error('Message too long');
  2195. return false;
  2196. }
  2197. // EME-PKCS1-v1_5 encoding
  2198. $psLen = $this->k - $mLen - 3;
  2199. $ps = '';
  2200. while (strlen($ps) != $psLen) {
  2201. $temp = crypt_random_string($psLen - strlen($ps));
  2202. $temp = str_replace("\x00", '', $temp);
  2203. $ps.= $temp;
  2204. }
  2205. $type = 2;
  2206. // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  2207. if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
  2208. $type = 1;
  2209. // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  2210. $ps = str_repeat("\xFF", $psLen);
  2211. }
  2212. $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  2213. // RSA encryption
  2214. $m = $this->_os2ip($em);
  2215. $c = $this->_rsaep($m);
  2216. $c = $this->_i2osp($c, $this->k);
  2217. // Output the ciphertext C
  2218. return $c;
  2219. }
  2220. /**
  2221. * RSAES-PKCS1-V1_5-DECRYPT
  2222. *
  2223. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  2224. *
  2225. * For compatibility purposes, this function departs slightly from the description given in RFC3447.
  2226. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  2227. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  2228. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  2229. * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
  2230. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  2231. *
  2232. * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
  2233. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  2234. * not private key encrypted ciphertext's.
  2235. *
  2236. * @access private
  2237. * @param String $c
  2238. * @return String
  2239. */
  2240. function _rsaes_pkcs1_v1_5_decrypt($c)
  2241. {
  2242. // Length checking
  2243. if (strlen($c) != $this->k) { // or if k < 11
  2244. user_error('Decryption error');
  2245. return false;
  2246. }
  2247. // RSA decryption
  2248. $c = $this->_os2ip($c);
  2249. $m = $this->_rsadp($c);
  2250. if ($m === false) {
  2251. user_error('Decryption error');
  2252. return false;
  2253. }
  2254. $em = $this->_i2osp($m, $this->k);
  2255. // EME-PKCS1-v1_5 decoding
  2256. if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  2257. user_error('Decryption error');
  2258. return false;
  2259. }
  2260. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  2261. $m = substr($em, strlen($ps) + 3);
  2262. if (strlen($ps) < 8) {
  2263. user_error('Decryption error');
  2264. return false;
  2265. }
  2266. // Output M
  2267. return $m;
  2268. }
  2269. /**
  2270. * EMSA-PSS-ENCODE
  2271. *
  2272. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  2273. *
  2274. * @access private
  2275. * @param String $m
  2276. * @param Integer $emBits
  2277. */
  2278. function _emsa_pss_encode($m, $emBits)
  2279. {
  2280. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2281. // be output.
  2282. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  2283. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  2284. $mHash = $this->hash->hash($m);
  2285. if ($emLen < $this->hLen + $sLen + 2) {
  2286. user_error('Encoding error');
  2287. return false;
  2288. }
  2289. $salt = crypt_random_string($sLen);
  2290. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2291. $h = $this->hash->hash($m2);
  2292. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  2293. $db = $ps . chr(1) . $salt;
  2294. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2295. $maskedDB = $db ^ $dbMask;
  2296. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  2297. $em = $maskedDB . $h . chr(0xBC);
  2298. return $em;
  2299. }
  2300. /**
  2301. * EMSA-PSS-VERIFY
  2302. *
  2303. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  2304. *
  2305. * @access private
  2306. * @param String $m
  2307. * @param String $em
  2308. * @param Integer $emBits
  2309. * @return String
  2310. */
  2311. function _emsa_pss_verify($m, $em, $emBits)
  2312. {
  2313. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2314. // be output.
  2315. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  2316. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  2317. $mHash = $this->hash->hash($m);
  2318. if ($emLen < $this->hLen + $sLen + 2) {
  2319. return false;
  2320. }
  2321. if ($em[strlen($em) - 1] != chr(0xBC)) {
  2322. return false;
  2323. }
  2324. $maskedDB = substr($em, 0, -$this->hLen - 1);
  2325. $h = substr($em, -$this->hLen - 1, $this->hLen);
  2326. $temp = chr(0xFF << ($emBits & 7));
  2327. if ((~$maskedDB[0] & $temp) != $temp) {
  2328. return false;
  2329. }
  2330. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2331. $db = $maskedDB ^ $dbMask;
  2332. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  2333. $temp = $emLen - $this->hLen - $sLen - 2;
  2334. if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  2335. return false;
  2336. }
  2337. $salt = substr($db, $temp + 1); // should be $sLen long
  2338. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2339. $h2 = $this->hash->hash($m2);
  2340. return $this->_equals($h, $h2);
  2341. }
  2342. /**
  2343. * RSASSA-PSS-SIGN
  2344. *
  2345. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  2346. *
  2347. * @access private
  2348. * @param String $m
  2349. * @return String
  2350. */
  2351. function _rsassa_pss_sign($m)
  2352. {
  2353. // EMSA-PSS encoding
  2354. $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  2355. // RSA signature
  2356. $m = $this->_os2ip($em);
  2357. $s = $this->_rsasp1($m);
  2358. $s = $this->_i2osp($s, $this->k);
  2359. // Output the signature S
  2360. return $s;
  2361. }
  2362. /**
  2363. * RSASSA-PSS-VERIFY
  2364. *
  2365. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  2366. *
  2367. * @access private
  2368. * @param String $m
  2369. * @param String $s
  2370. * @return String
  2371. */
  2372. function _rsassa_pss_verify($m, $s)
  2373. {
  2374. // Length checking
  2375. if (strlen($s) != $this->k) {
  2376. user_error('Invalid signature');
  2377. return false;
  2378. }
  2379. // RSA verification
  2380. $modBits = 8 * $this->k;
  2381. $s2 = $this->_os2ip($s);
  2382. $m2 = $this->_rsavp1($s2);
  2383. if ($m2 === false) {
  2384. user_error('Invalid signature');
  2385. return false;
  2386. }
  2387. $em = $this->_i2osp($m2, $modBits >> 3);
  2388. if ($em === false) {
  2389. user_error('Invalid signature');
  2390. return false;
  2391. }
  2392. // EMSA-PSS verification
  2393. return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  2394. }
  2395. /**
  2396. * EMSA-PKCS1-V1_5-ENCODE
  2397. *
  2398. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  2399. *
  2400. * @access private
  2401. * @param String $m
  2402. * @param Integer $emLen
  2403. * @return String
  2404. */
  2405. function _emsa_pkcs1_v1_5_encode($m, $emLen)
  2406. {
  2407. $h = $this->hash->hash($m);
  2408. if ($h === false) {
  2409. return false;
  2410. }
  2411. // see http://tools.ietf.org/html/rfc3447#page-43
  2412. switch ($this->hashName) {
  2413. case 'md2':
  2414. $t = pack('H*', '3020300c06082a864886f70d020205000410');
  2415. break;
  2416. case 'md5':
  2417. $t = pack('H*', '3020300c06082a864886f70d020505000410');
  2418. break;
  2419. case 'sha1':
  2420. $t = pack('H*', '3021300906052b0e03021a05000414');
  2421. break;
  2422. case 'sha256':
  2423. $t = pack('H*', '3031300d060960864801650304020105000420');
  2424. break;
  2425. case 'sha384':
  2426. $t = pack('H*', '3041300d060960864801650304020205000430');
  2427. break;
  2428. case 'sha512':
  2429. $t = pack('H*', '3051300d060960864801650304020305000440');
  2430. }
  2431. $t.= $h;
  2432. $tLen = strlen($t);
  2433. if ($emLen < $tLen + 11) {
  2434. user_error('Intended encoded message length too short');
  2435. return false;
  2436. }
  2437. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  2438. $em = "\0\1$ps\0$t";
  2439. return $em;
  2440. }
  2441. /**
  2442. * RSASSA-PKCS1-V1_5-SIGN
  2443. *
  2444. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  2445. *
  2446. * @access private
  2447. * @param String $m
  2448. * @return String
  2449. */
  2450. function _rsassa_pkcs1_v1_5_sign($m)
  2451. {
  2452. // EMSA-PKCS1-v1_5 encoding
  2453. $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2454. if ($em === false) {
  2455. user_error('RSA modulus too short');
  2456. return false;
  2457. }
  2458. // RSA signature
  2459. $m = $this->_os2ip($em);
  2460. $s = $this->_rsasp1($m);
  2461. $s = $this->_i2osp($s, $this->k);
  2462. // Output the signature S
  2463. return $s;
  2464. }
  2465. /**
  2466. * RSASSA-PKCS1-V1_5-VERIFY
  2467. *
  2468. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  2469. *
  2470. * @access private
  2471. * @param String $m
  2472. * @return String
  2473. */
  2474. function _rsassa_pkcs1_v1_5_verify($m, $s)
  2475. {
  2476. // Length checking
  2477. if (strlen($s) != $this->k) {
  2478. user_error('Invalid signature');
  2479. return false;
  2480. }
  2481. // RSA verification
  2482. $s = $this->_os2ip($s);
  2483. $m2 = $this->_rsavp1($s);
  2484. if ($m2 === false) {
  2485. user_error('Invalid signature');
  2486. return false;
  2487. }
  2488. $em = $this->_i2osp($m2, $this->k);
  2489. if ($em === false) {
  2490. user_error('Invalid signature');
  2491. return false;
  2492. }
  2493. // EMSA-PKCS1-v1_5 encoding
  2494. $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2495. if ($em2 === false) {
  2496. user_error('RSA modulus too short');
  2497. return false;
  2498. }
  2499. // Compare
  2500. return $this->_equals($em, $em2);
  2501. }
  2502. /**
  2503. * Set Encryption Mode
  2504. *
  2505. * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
  2506. *
  2507. * @access public
  2508. * @param Integer $mode
  2509. */
  2510. function setEncryptionMode($mode)
  2511. {
  2512. $this->encryptionMode = $mode;
  2513. }
  2514. /**
  2515. * Set Signature Mode
  2516. *
  2517. * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
  2518. *
  2519. * @access public
  2520. * @param Integer $mode
  2521. */
  2522. function setSignatureMode($mode)
  2523. {
  2524. $this->signatureMode = $mode;
  2525. }
  2526. /**
  2527. * Set public key comment.
  2528. *
  2529. * @access public
  2530. * @param String $comment
  2531. */
  2532. function setComment($comment)
  2533. {
  2534. $this->comment = $comment;
  2535. }
  2536. /**
  2537. * Get public key comment.
  2538. *
  2539. * @access public
  2540. * @return String
  2541. */
  2542. function getComment()
  2543. {
  2544. return $this->comment;
  2545. }
  2546. /**
  2547. * Encryption
  2548. *
  2549. * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
  2550. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  2551. * be concatenated together.
  2552. *
  2553. * @see decrypt()
  2554. * @access public
  2555. * @param String $plaintext
  2556. * @return String
  2557. */
  2558. function encrypt($plaintext)
  2559. {
  2560. switch ($this->encryptionMode) {
  2561. case CRYPT_RSA_ENCRYPTION_PKCS1:
  2562. $length = $this->k - 11;
  2563. if ($length <= 0) {
  2564. return false;
  2565. }
  2566. $plaintext = str_split($plaintext, $length);
  2567. $ciphertext = '';
  2568. foreach ($plaintext as $m) {
  2569. $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
  2570. }
  2571. return $ciphertext;
  2572. //case CRYPT_RSA_ENCRYPTION_OAEP:
  2573. default:
  2574. $length = $this->k - 2 * $this->hLen - 2;
  2575. if ($length <= 0) {
  2576. return false;
  2577. }
  2578. $plaintext = str_split($plaintext, $length);
  2579. $ciphertext = '';
  2580. foreach ($plaintext as $m) {
  2581. $ciphertext.= $this->_rsaes_oaep_encrypt($m);
  2582. }
  2583. return $ciphertext;
  2584. }
  2585. }
  2586. /**
  2587. * Decryption
  2588. *
  2589. * @see encrypt()
  2590. * @access public
  2591. * @param String $plaintext
  2592. * @return String
  2593. */
  2594. function decrypt($ciphertext)
  2595. {
  2596. if ($this->k <= 0) {
  2597. return false;
  2598. }
  2599. $ciphertext = str_split($ciphertext, $this->k);
  2600. $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
  2601. $plaintext = '';
  2602. switch ($this->encryptionMode) {
  2603. case CRYPT_RSA_ENCRYPTION_PKCS1:
  2604. $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
  2605. break;
  2606. //case CRYPT_RSA_ENCRYPTION_OAEP:
  2607. default:
  2608. $decrypt = '_rsaes_oaep_decrypt';
  2609. }
  2610. foreach ($ciphertext as $c) {
  2611. $temp = $this->$decrypt($c);
  2612. if ($temp === false) {
  2613. return false;
  2614. }
  2615. $plaintext.= $temp;
  2616. }
  2617. return $plaintext;
  2618. }
  2619. /**
  2620. * Create a signature
  2621. *
  2622. * @see verify()
  2623. * @access public
  2624. * @param String $message
  2625. * @return String
  2626. */
  2627. function sign($message)
  2628. {
  2629. if (empty($this->modulus) || empty($this->exponent)) {
  2630. return false;
  2631. }
  2632. switch ($this->signatureMode) {
  2633. case CRYPT_RSA_SIGNATURE_PKCS1:
  2634. return $this->_rsassa_pkcs1_v1_5_sign($message);
  2635. //case CRYPT_RSA_SIGNATURE_PSS:
  2636. default:
  2637. return $this->_rsassa_pss_sign($message);
  2638. }
  2639. }
  2640. /**
  2641. * Verifies a signature
  2642. *
  2643. * @see sign()
  2644. * @access public
  2645. * @param String $message
  2646. * @param String $signature
  2647. * @return Boolean
  2648. */
  2649. function verify($message, $signature)
  2650. {
  2651. if (empty($this->modulus) || empty($this->exponent)) {
  2652. return false;
  2653. }
  2654. switch ($this->signatureMode) {
  2655. case CRYPT_RSA_SIGNATURE_PKCS1:
  2656. return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  2657. //case CRYPT_RSA_SIGNATURE_PSS:
  2658. default:
  2659. return $this->_rsassa_pss_verify($message, $signature);
  2660. }
  2661. }
  2662. /**
  2663. * Extract raw BER from Base64 encoding
  2664. *
  2665. * @access private
  2666. * @param String $str
  2667. * @return String
  2668. */
  2669. function _extractBER($str)
  2670. {
  2671. /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them
  2672. * above and beyond the ceritificate.
  2673. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line:
  2674. *
  2675. * Bag Attributes
  2676. * localKeyID: 01 00 00 00
  2677. * subject=/O=organization/OU=org unit/CN=common name
  2678. * issuer=/O=organization/CN=common name
  2679. */
  2680. $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1);
  2681. // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
  2682. $temp = preg_replace('#-+[^-]+-+#', '', $temp);
  2683. // remove new lines
  2684. $temp = str_replace(array("\r", "\n", ' '), '', $temp);
  2685. $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
  2686. return $temp != false ? $temp : $str;
  2687. }
  2688. }