PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://github.com/phocode/my_reddit
PHP | 2990 lines | 1582 code | 294 blank | 1114 comment | 280 complexity | f3373a03929df88dd6d5e71e409cb834 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause

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

  1. <?php
  2. /**
  3. * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * Here's an example of how to encrypt and decrypt text with this library:
  8. * <code>
  9. * <?php
  10. * include 'Crypt/RSA.php';
  11. *
  12. * $rsa = new Crypt_RSA();
  13. * extract($rsa->createKey());
  14. *
  15. * $plaintext = 'terrafrost';
  16. *
  17. * $rsa->loadKey($privatekey);
  18. * $ciphertext = $rsa->encrypt($plaintext);
  19. *
  20. * $rsa->loadKey($publickey);
  21. * echo $rsa->decrypt($ciphertext);
  22. * ?>
  23. * </code>
  24. *
  25. * Here's an example of how to create signatures and verify signatures with this library:
  26. * <code>
  27. * <?php
  28. * include 'Crypt/RSA.php';
  29. *
  30. * $rsa = new Crypt_RSA();
  31. * extract($rsa->createKey());
  32. *
  33. * $plaintext = 'terrafrost';
  34. *
  35. * $rsa->loadKey($privatekey);
  36. * $signature = $rsa->sign($plaintext);
  37. *
  38. * $rsa->loadKey($publickey);
  39. * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
  40. * ?>
  41. * </code>
  42. *
  43. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  44. * of this software and associated documentation files (the "Software"), to deal
  45. * in the Software without restriction, including without limitation the rights
  46. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  47. * copies of the Software, and to permit persons to whom the Software is
  48. * furnished to do so, subject to the following conditions:
  49. *
  50. * The above copyright notice and this permission notice shall be included in
  51. * all copies or substantial portions of the Software.
  52. *
  53. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  54. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  55. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  56. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  57. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  58. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  59. * THE SOFTWARE.
  60. *
  61. * @category Crypt
  62. * @package Crypt_RSA
  63. * @author Jim Wigginton <terrafrost@php.net>
  64. * @copyright MMIX Jim Wigginton
  65. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  66. * @link http://phpseclib.sourceforge.net
  67. */
  68. /**
  69. * Include Crypt_Random
  70. */
  71. // the class_exists() will only be called if the crypt_random_string function hasn't been defined and
  72. // will trigger a call to __autoload() if you're wanting to auto-load classes
  73. // call function_exists() a second time to stop the include_once from being called outside
  74. // of the auto loader
  75. if (!function_exists('crypt_random_string')) {
  76. include_once 'Random.php';
  77. }
  78. /**
  79. * Include Crypt_Hash
  80. */
  81. if (!class_exists('Crypt_Hash')) {
  82. include_once 'Hash.php';
  83. }
  84. /**#@+
  85. * @access public
  86. * @see Crypt_RSA::encrypt()
  87. * @see Crypt_RSA::decrypt()
  88. */
  89. /**
  90. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  91. * (OAEP) for encryption / decryption.
  92. *
  93. * Uses sha1 by default.
  94. *
  95. * @see Crypt_RSA::setHash()
  96. * @see Crypt_RSA::setMGFHash()
  97. */
  98. define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
  99. /**
  100. * Use PKCS#1 padding.
  101. *
  102. * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  103. * compatibility with protocols (like SSH-1) written before OAEP's introduction.
  104. */
  105. define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
  106. /**#@-*/
  107. /**#@+
  108. * @access public
  109. * @see Crypt_RSA::sign()
  110. * @see Crypt_RSA::verify()
  111. * @see Crypt_RSA::setHash()
  112. */
  113. /**
  114. * Use the Probabilistic Signature Scheme for signing
  115. *
  116. * Uses sha1 by default.
  117. *
  118. * @see Crypt_RSA::setSaltLength()
  119. * @see Crypt_RSA::setMGFHash()
  120. */
  121. define('CRYPT_RSA_SIGNATURE_PSS', 1);
  122. /**
  123. * Use the PKCS#1 scheme by default.
  124. *
  125. * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  126. * compatibility with protocols (like SSH-2) written before PSS's introduction.
  127. */
  128. define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
  129. /**#@-*/
  130. /**#@+
  131. * @access private
  132. * @see Crypt_RSA::createKey()
  133. */
  134. /**
  135. * ASN1 Integer
  136. */
  137. define('CRYPT_RSA_ASN1_INTEGER', 2);
  138. /**
  139. * ASN1 Bit String
  140. */
  141. define('CRYPT_RSA_ASN1_BITSTRING', 3);
  142. /**
  143. * ASN1 Octet String
  144. */
  145. define('CRYPT_RSA_ASN1_OCTETSTRING', 4);
  146. /**
  147. * ASN1 Object Identifier
  148. */
  149. define('CRYPT_RSA_ASN1_OBJECT', 6);
  150. /**
  151. * ASN1 Sequence (with the constucted bit set)
  152. */
  153. define('CRYPT_RSA_ASN1_SEQUENCE', 48);
  154. /**#@-*/
  155. /**#@+
  156. * @access private
  157. * @see Crypt_RSA::Crypt_RSA()
  158. */
  159. /**
  160. * To use the pure-PHP implementation
  161. */
  162. define('CRYPT_RSA_MODE_INTERNAL', 1);
  163. /**
  164. * To use the OpenSSL library
  165. *
  166. * (if enabled; otherwise, the internal implementation will be used)
  167. */
  168. define('CRYPT_RSA_MODE_OPENSSL', 2);
  169. /**#@-*/
  170. /**
  171. * Default openSSL configuration file.
  172. */
  173. define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/../openssl.cnf');
  174. /**#@+
  175. * @access public
  176. * @see Crypt_RSA::createKey()
  177. * @see Crypt_RSA::setPrivateKeyFormat()
  178. */
  179. /**
  180. * PKCS#1 formatted private key
  181. *
  182. * Used by OpenSSH
  183. */
  184. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
  185. /**
  186. * PuTTY formatted private key
  187. */
  188. define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
  189. /**
  190. * XML formatted private key
  191. */
  192. define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
  193. /**
  194. * PKCS#8 formatted private key
  195. */
  196. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS8', 3);
  197. /**#@-*/
  198. /**#@+
  199. * @access public
  200. * @see Crypt_RSA::createKey()
  201. * @see Crypt_RSA::setPublicKeyFormat()
  202. */
  203. /**
  204. * Raw public key
  205. *
  206. * An array containing two Math_BigInteger objects.
  207. *
  208. * The exponent can be indexed with any of the following:
  209. *
  210. * 0, e, exponent, publicExponent
  211. *
  212. * The modulus can be indexed with any of the following:
  213. *
  214. * 1, n, modulo, modulus
  215. */
  216. define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
  217. /**
  218. * PKCS#1 formatted public key (raw)
  219. *
  220. * Used by File/X509.php
  221. *
  222. * Has the following header:
  223. *
  224. * -----BEGIN RSA PUBLIC KEY-----
  225. *
  226. * Analogous to ssh-keygen's pem format (as specified by -m)
  227. */
  228. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 4);
  229. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4);
  230. /**
  231. * XML formatted public key
  232. */
  233. define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
  234. /**
  235. * OpenSSH formatted public key
  236. *
  237. * Place in $HOME/.ssh/authorized_keys
  238. */
  239. define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
  240. /**
  241. * PKCS#1 formatted public key (encapsulated)
  242. *
  243. * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
  244. *
  245. * Has the following header:
  246. *
  247. * -----BEGIN PUBLIC KEY-----
  248. *
  249. * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
  250. * is specific to private keys it's basically creating a DER-encoded wrapper
  251. * for keys. This just extends that same concept to public keys (much like ssh-keygen)
  252. */
  253. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS8', 7);
  254. /**#@-*/
  255. /**
  256. * Pure-PHP PKCS#1 compliant implementation of RSA.
  257. *
  258. * @package Crypt_RSA
  259. * @author Jim Wigginton <terrafrost@php.net>
  260. * @access public
  261. */
  262. class Crypt_RSA
  263. {
  264. /**
  265. * Precomputed Zero
  266. *
  267. * @var Array
  268. * @access private
  269. */
  270. var $zero;
  271. /**
  272. * Precomputed One
  273. *
  274. * @var Array
  275. * @access private
  276. */
  277. var $one;
  278. /**
  279. * Private Key Format
  280. *
  281. * @var Integer
  282. * @access private
  283. */
  284. var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  285. /**
  286. * Public Key Format
  287. *
  288. * @var Integer
  289. * @access public
  290. */
  291. var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS8;
  292. /**
  293. * Modulus (ie. n)
  294. *
  295. * @var Math_BigInteger
  296. * @access private
  297. */
  298. var $modulus;
  299. /**
  300. * Modulus length
  301. *
  302. * @var Math_BigInteger
  303. * @access private
  304. */
  305. var $k;
  306. /**
  307. * Exponent (ie. e or d)
  308. *
  309. * @var Math_BigInteger
  310. * @access private
  311. */
  312. var $exponent;
  313. /**
  314. * Primes for Chinese Remainder Theorem (ie. p and q)
  315. *
  316. * @var Array
  317. * @access private
  318. */
  319. var $primes;
  320. /**
  321. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  322. *
  323. * @var Array
  324. * @access private
  325. */
  326. var $exponents;
  327. /**
  328. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  329. *
  330. * @var Array
  331. * @access private
  332. */
  333. var $coefficients;
  334. /**
  335. * Hash name
  336. *
  337. * @var String
  338. * @access private
  339. */
  340. var $hashName;
  341. /**
  342. * Hash function
  343. *
  344. * @var Crypt_Hash
  345. * @access private
  346. */
  347. var $hash;
  348. /**
  349. * Length of hash function output
  350. *
  351. * @var Integer
  352. * @access private
  353. */
  354. var $hLen;
  355. /**
  356. * Length of salt
  357. *
  358. * @var Integer
  359. * @access private
  360. */
  361. var $sLen;
  362. /**
  363. * Hash function for the Mask Generation Function
  364. *
  365. * @var Crypt_Hash
  366. * @access private
  367. */
  368. var $mgfHash;
  369. /**
  370. * Length of MGF hash function output
  371. *
  372. * @var Integer
  373. * @access private
  374. */
  375. var $mgfHLen;
  376. /**
  377. * Encryption mode
  378. *
  379. * @var Integer
  380. * @access private
  381. */
  382. var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  383. /**
  384. * Signature mode
  385. *
  386. * @var Integer
  387. * @access private
  388. */
  389. var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  390. /**
  391. * Public Exponent
  392. *
  393. * @var Mixed
  394. * @access private
  395. */
  396. var $publicExponent = false;
  397. /**
  398. * Password
  399. *
  400. * @var String
  401. * @access private
  402. */
  403. var $password = false;
  404. /**
  405. * Components
  406. *
  407. * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
  408. * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
  409. *
  410. * @see Crypt_RSA::_start_element_handler()
  411. * @var Array
  412. * @access private
  413. */
  414. var $components = array();
  415. /**
  416. * Current String
  417. *
  418. * For use with parsing XML formatted keys.
  419. *
  420. * @see Crypt_RSA::_character_handler()
  421. * @see Crypt_RSA::_stop_element_handler()
  422. * @var Mixed
  423. * @access private
  424. */
  425. var $current;
  426. /**
  427. * OpenSSL configuration file name.
  428. *
  429. * Set to null to use system configuration file.
  430. * @see Crypt_RSA::createKey()
  431. * @var Mixed
  432. * @Access public
  433. */
  434. var $configFile;
  435. /**
  436. * Public key comment field.
  437. *
  438. * @var String
  439. * @access private
  440. */
  441. var $comment = 'phpseclib-generated-key';
  442. /**
  443. * The constructor
  444. *
  445. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  446. * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  447. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  448. *
  449. * @return Crypt_RSA
  450. * @access public
  451. */
  452. function Crypt_RSA()
  453. {
  454. if (!class_exists('Math_BigInteger')) {
  455. include_once 'Math/BigInteger.php';
  456. }
  457. $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
  458. if ( !defined('CRYPT_RSA_MODE') ) {
  459. switch (true) {
  460. // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
  461. // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
  462. // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
  463. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
  464. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  465. break;
  466. // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0
  467. case !function_exists('openssl_pkey_get_details'):
  468. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  469. break;
  470. case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
  471. // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
  472. ob_start();
  473. @phpinfo();
  474. $content = ob_get_contents();
  475. ob_end_clean();
  476. preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
  477. $versions = array();
  478. if (!empty($matches[1])) {
  479. for ($i = 0; $i < count($matches[1]); $i++) {
  480. $versions[$matches[1][$i]] = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
  481. }
  482. }
  483. // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
  484. switch (true) {
  485. case !isset($versions['Header']):
  486. case !isset($versions['Library']):
  487. case $versions['Header'] == $versions['Library']:
  488. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  489. break;
  490. default:
  491. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  492. define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
  493. }
  494. break;
  495. default:
  496. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  497. }
  498. }
  499. $this->zero = new Math_BigInteger();
  500. $this->one = new Math_BigInteger(1);
  501. $this->hash = new Crypt_Hash('sha1');
  502. $this->hLen = $this->hash->getLength();
  503. $this->hashName = 'sha1';
  504. $this->mgfHash = new Crypt_Hash('sha1');
  505. $this->mgfHLen = $this->mgfHash->getLength();
  506. }
  507. /**
  508. * Create public / private key pair
  509. *
  510. * Returns an array with the following three elements:
  511. * - 'privatekey': The private key.
  512. * - 'publickey': The public key.
  513. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  514. * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  515. *
  516. * @access public
  517. * @param optional Integer $bits
  518. * @param optional Integer $timeout
  519. * @param optional Math_BigInteger $p
  520. */
  521. function createKey($bits = 1024, $timeout = false, $partial = array())
  522. {
  523. if (!defined('CRYPT_RSA_EXPONENT')) {
  524. // http://en.wikipedia.org/wiki/65537_%28number%29
  525. define('CRYPT_RSA_EXPONENT', '65537');
  526. }
  527. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  528. // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
  529. // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
  530. // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
  531. // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
  532. // generation when there's a chance neither gmp nor OpenSSL are installed)
  533. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  534. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  535. }
  536. // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  537. if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
  538. $config = array();
  539. if (isset($this->configFile)) {
  540. $config['config'] = $this->configFile;
  541. }
  542. $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
  543. openssl_pkey_export($rsa, $privatekey, null, $config);
  544. $publickey = openssl_pkey_get_details($rsa);
  545. $publickey = $publickey['key'];
  546. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  547. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  548. // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  549. while (openssl_error_string() !== false);
  550. return array(
  551. 'privatekey' => $privatekey,
  552. 'publickey' => $publickey,
  553. 'partialkey' => false
  554. );
  555. }
  556. static $e;
  557. if (!isset($e)) {
  558. $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
  559. }
  560. extract($this->_generateMinMax($bits));
  561. $absoluteMin = $min;
  562. $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
  563. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  564. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  565. $temp = CRYPT_RSA_SMALLEST_PRIME;
  566. } else {
  567. $num_primes = 2;
  568. }
  569. extract($this->_generateMinMax($temp + $bits % $temp));
  570. $finalMax = $max;
  571. extract($this->_generateMinMax($temp));
  572. $generator = new Math_BigInteger();
  573. $n = $this->one->copy();
  574. if (!empty($partial)) {
  575. extract(unserialize($partial));
  576. } else {
  577. $exponents = $coefficients = $primes = array();
  578. $lcm = array(
  579. 'top' => $this->one->copy(),
  580. 'bottom' => false
  581. );
  582. }
  583. $start = time();
  584. $i0 = count($primes) + 1;
  585. do {
  586. for ($i = $i0; $i <= $num_primes; $i++) {
  587. if ($timeout !== false) {
  588. $timeout-= time() - $start;
  589. $start = time();
  590. if ($timeout <= 0) {
  591. return array(
  592. 'privatekey' => '',
  593. 'publickey' => '',
  594. 'partialkey' => serialize(array(
  595. 'primes' => $primes,
  596. 'coefficients' => $coefficients,
  597. 'lcm' => $lcm,
  598. 'exponents' => $exponents
  599. ))
  600. );
  601. }
  602. }
  603. if ($i == $num_primes) {
  604. list($min, $temp) = $absoluteMin->divide($n);
  605. if (!$temp->equals($this->zero)) {
  606. $min = $min->add($this->one); // ie. ceil()
  607. }
  608. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  609. } else {
  610. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  611. }
  612. if ($primes[$i] === false) { // if we've reached the timeout
  613. if (count($primes) > 1) {
  614. $partialkey = '';
  615. } else {
  616. array_pop($primes);
  617. $partialkey = serialize(array(
  618. 'primes' => $primes,
  619. 'coefficients' => $coefficients,
  620. 'lcm' => $lcm,
  621. 'exponents' => $exponents
  622. ));
  623. }
  624. return array(
  625. 'privatekey' => '',
  626. 'publickey' => '',
  627. 'partialkey' => $partialkey
  628. );
  629. }
  630. // the first coefficient is calculated differently from the rest
  631. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  632. if ($i > 2) {
  633. $coefficients[$i] = $n->modInverse($primes[$i]);
  634. }
  635. $n = $n->multiply($primes[$i]);
  636. $temp = $primes[$i]->subtract($this->one);
  637. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  638. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  639. $lcm['top'] = $lcm['top']->multiply($temp);
  640. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  641. $exponents[$i] = $e->modInverse($temp);
  642. }
  643. list($temp) = $lcm['top']->divide($lcm['bottom']);
  644. $gcd = $temp->gcd($e);
  645. $i0 = 1;
  646. } while (!$gcd->equals($this->one));
  647. $d = $e->modInverse($temp);
  648. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  649. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  650. // RSAPrivateKey ::= SEQUENCE {
  651. // version Version,
  652. // modulus INTEGER, -- n
  653. // publicExponent INTEGER, -- e
  654. // privateExponent INTEGER, -- d
  655. // prime1 INTEGER, -- p
  656. // prime2 INTEGER, -- q
  657. // exponent1 INTEGER, -- d mod (p-1)
  658. // exponent2 INTEGER, -- d mod (q-1)
  659. // coefficient INTEGER, -- (inverse of q) mod p
  660. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  661. // }
  662. return array(
  663. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  664. 'publickey' => $this->_convertPublicKey($n, $e),
  665. 'partialkey' => false
  666. );
  667. }
  668. /**
  669. * Convert a private key to the appropriate format.
  670. *
  671. * @access private
  672. * @see setPrivateKeyFormat()
  673. * @param String $RSAPrivateKey
  674. * @return String
  675. */
  676. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  677. {
  678. $signed = $this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_XML;
  679. $num_primes = count($primes);
  680. $raw = array(
  681. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  682. 'modulus' => $n->toBytes($signed),
  683. 'publicExponent' => $e->toBytes($signed),
  684. 'privateExponent' => $d->toBytes($signed),
  685. 'prime1' => $primes[1]->toBytes($signed),
  686. 'prime2' => $primes[2]->toBytes($signed),
  687. 'exponent1' => $exponents[1]->toBytes($signed),
  688. 'exponent2' => $exponents[2]->toBytes($signed),
  689. 'coefficient' => $coefficients[2]->toBytes($signed)
  690. );
  691. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  692. // call _convertPublicKey() instead.
  693. switch ($this->privateKeyFormat) {
  694. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  695. if ($num_primes != 2) {
  696. return false;
  697. }
  698. return "<RSAKeyValue>\r\n" .
  699. ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
  700. ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
  701. ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
  702. ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
  703. ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
  704. ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
  705. ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
  706. ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
  707. '</RSAKeyValue>';
  708. break;
  709. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  710. if ($num_primes != 2) {
  711. return false;
  712. }
  713. $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
  714. $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
  715. $key.= $encryption;
  716. $key.= "\r\nComment: " . $this->comment . "\r\n";
  717. $public = pack('Na*Na*Na*',
  718. strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
  719. );
  720. $source = pack('Na*Na*Na*Na*',
  721. strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption,
  722. strlen($this->comment), $this->comment, strlen($public), $public
  723. );
  724. $public = base64_encode($public);
  725. $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
  726. $key.= chunk_split($public, 64);
  727. $private = pack('Na*Na*Na*Na*',
  728. strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'],
  729. strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
  730. );
  731. if (empty($this->password) && !is_string($this->password)) {
  732. $source.= pack('Na*', strlen($private), $private);
  733. $hashkey = 'putty-private-key-file-mac-key';
  734. } else {
  735. $private.= crypt_random_string(16 - (strlen($private) & 15));
  736. $source.= pack('Na*', strlen($private), $private);
  737. if (!class_exists('Crypt_AES')) {
  738. include_once 'Crypt/AES.php';
  739. }
  740. $sequence = 0;
  741. $symkey = '';
  742. while (strlen($symkey) < 32) {
  743. $temp = pack('Na*', $sequence++, $this->password);
  744. $symkey.= pack('H*', sha1($temp));
  745. }
  746. $symkey = substr($symkey, 0, 32);
  747. $crypto = new Crypt_AES();
  748. $crypto->setKey($symkey);
  749. $crypto->disablePadding();
  750. $private = $crypto->encrypt($private);
  751. $hashkey = 'putty-private-key-file-mac-key' . $this->password;
  752. }
  753. $private = base64_encode($private);
  754. $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
  755. $key.= chunk_split($private, 64);
  756. if (!class_exists('Crypt_Hash')) {
  757. include_once 'Crypt/Hash.php';
  758. }
  759. $hash = new Crypt_Hash('sha1');
  760. $hash->setKey(pack('H*', sha1($hashkey)));
  761. $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
  762. return $key;
  763. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  764. $components = array();
  765. foreach ($raw as $name => $value) {
  766. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  767. }
  768. $RSAPrivateKey = implode('', $components);
  769. if ($num_primes > 2) {
  770. $OtherPrimeInfos = '';
  771. for ($i = 3; $i <= $num_primes; $i++) {
  772. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  773. //
  774. // OtherPrimeInfo ::= SEQUENCE {
  775. // prime INTEGER, -- ri
  776. // exponent INTEGER, -- di
  777. // coefficient INTEGER -- ti
  778. // }
  779. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  780. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  781. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  782. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  783. }
  784. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  785. }
  786. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  787. if ($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8) {
  788. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  789. $RSAPrivateKey = pack('Ca*a*Ca*a*',
  790. CRYPT_RSA_ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  791. );
  792. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  793. if (!empty($this->password) || is_string($this->password)) {
  794. $salt = crypt_random_string(8);
  795. $iterationCount = 2048;
  796. if (!class_exists('Crypt_DES')) {
  797. include_once 'Crypt/DES.php';
  798. }
  799. $crypto = new Crypt_DES();
  800. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  801. $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
  802. $parameters = pack('Ca*a*Ca*N',
  803. CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt,
  804. CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(4), $iterationCount
  805. );
  806. $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
  807. $encryptionAlgorithm = pack('Ca*a*Ca*a*',
  808. CRYPT_RSA_ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC,
  809. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters
  810. );
  811. $RSAPrivateKey = pack('Ca*a*Ca*a*',
  812. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm,
  813. CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  814. );
  815. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  816. $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" .
  817. chunk_split(base64_encode($RSAPrivateKey), 64) .
  818. '-----END ENCRYPTED PRIVATE KEY-----';
  819. } else {
  820. $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" .
  821. chunk_split(base64_encode($RSAPrivateKey), 64) .
  822. '-----END PRIVATE KEY-----';
  823. }
  824. return $RSAPrivateKey;
  825. }
  826. if (!empty($this->password) || is_string($this->password)) {
  827. $iv = crypt_random_string(8);
  828. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  829. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  830. if (!class_exists('Crypt_TripleDES')) {
  831. include_once 'Crypt/TripleDES.php';
  832. }
  833. $des = new Crypt_TripleDES();
  834. $des->setKey($symkey);
  835. $des->setIV($iv);
  836. $iv = strtoupper(bin2hex($iv));
  837. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  838. "Proc-Type: 4,ENCRYPTED\r\n" .
  839. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  840. "\r\n" .
  841. chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
  842. '-----END RSA PRIVATE KEY-----';
  843. } else {
  844. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  845. chunk_split(base64_encode($RSAPrivateKey), 64) .
  846. '-----END RSA PRIVATE KEY-----';
  847. }
  848. return $RSAPrivateKey;
  849. }
  850. }
  851. /**
  852. * Convert a public key to the appropriate format
  853. *
  854. * @access private
  855. * @see setPublicKeyFormat()
  856. * @param String $RSAPrivateKey
  857. * @return String
  858. */
  859. function _convertPublicKey($n, $e)
  860. {
  861. $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML;
  862. $modulus = $n->toBytes($signed);
  863. $publicExponent = $e->toBytes($signed);
  864. switch ($this->publicKeyFormat) {
  865. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  866. return array('e' => $e->copy(), 'n' => $n->copy());
  867. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  868. return "<RSAKeyValue>\r\n" .
  869. ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
  870. ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
  871. '</RSAKeyValue>';
  872. break;
  873. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  874. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  875. // string "ssh-rsa"
  876. // mpint e
  877. // mpint n
  878. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  879. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
  880. return $RSAPublicKey;
  881. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  882. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  883. // RSAPublicKey ::= SEQUENCE {
  884. // modulus INTEGER, -- n
  885. // publicExponent INTEGER -- e
  886. // }
  887. $components = array(
  888. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  889. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  890. );
  891. $RSAPublicKey = pack('Ca*a*a*',
  892. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  893. $components['modulus'], $components['publicExponent']
  894. );
  895. if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) {
  896. $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
  897. chunk_split(base64_encode($RSAPublicKey), 64) .
  898. '-----END RSA PUBLIC KEY-----';
  899. } else {
  900. // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
  901. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  902. $RSAPublicKey = chr(0) . $RSAPublicKey;
  903. $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  904. $RSAPublicKey = pack('Ca*a*',
  905. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
  906. );
  907. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  908. chunk_split(base64_encode($RSAPublicKey), 64) .
  909. '-----END PUBLIC KEY-----';
  910. }
  911. return $RSAPublicKey;
  912. }
  913. }
  914. /**
  915. * Break a public or private key down into its constituant components
  916. *
  917. * @access private
  918. * @see _convertPublicKey()
  919. * @see _convertPrivateKey()
  920. * @param String $key
  921. * @param Integer $type
  922. * @return Array
  923. */
  924. function _parseKey($key, $type)
  925. {
  926. if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) {
  927. return false;
  928. }
  929. switch ($type) {
  930. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  931. if (!is_array($key)) {
  932. return false;
  933. }
  934. $components = array();
  935. switch (true) {
  936. case isset($key['e']):
  937. $components['publicExponent'] = $key['e']->copy();
  938. break;
  939. case isset($key['exponent']):
  940. $components['publicExponent'] = $key['exponent']->copy();
  941. break;
  942. case isset($key['publicExponent']):
  943. $components['publicExponent'] = $key['publicExponent']->copy();
  944. break;
  945. case isset($key[0]):
  946. $components['publicExponent'] = $key[0]->copy();
  947. }
  948. switch (true) {
  949. case isset($key['n']):
  950. $components['modulus'] = $key['n']->copy();
  951. break;
  952. case isset($key['modulo']):
  953. $components['modulus'] = $key['modulo']->copy();
  954. break;
  955. case isset($key['modulus']):
  956. $components['modulus'] = $key['modulus']->copy();
  957. break;
  958. case isset($key[1]):
  959. $components['modulus'] = $key[1]->copy();
  960. }
  961. return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
  962. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  963. case CRYPT_RSA_PRIVATE_FORMAT_PKCS8:
  964. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  965. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  966. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  967. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  968. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  969. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  970. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  971. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  972. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  973. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  974. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  975. implementation are part of the standard, as well.
  976. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  977. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  978. $iv = pack('H*', trim($matches[2]));
  979. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  980. $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
  981. // remove the Proc-Type / DEK-Info sections as they're no longer needed
  982. $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
  983. $ciphertext = $this->_extractBER($key);
  984. if ($ciphertext === false) {
  985. $ciphertext = $key;
  986. }
  987. switch ($matches[1]) {
  988. case 'AES-256-CBC':
  989. if (!class_exists('Crypt_AES')) {
  990. include_once 'Crypt/AES.php';
  991. }
  992. $crypto = new Crypt_AES();
  993. break;
  994. case 'AES-128-CBC':
  995. if (!class_exists('Crypt_AES')) {
  996. include_once 'Crypt/AES.php';
  997. }
  998. $symkey = substr($symkey, 0, 16);
  999. $crypto = new Crypt_AES();
  1000. break;
  1001. case 'DES-EDE3-CFB':
  1002. if (!class_exists('Crypt_TripleDES')) {
  1003. include_once 'Crypt/TripleDES.php';
  1004. }
  1005. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  1006. break;
  1007. case 'DES-EDE3-CBC':
  1008. if (!class_exists('Crypt_TripleDES')) {
  1009. include_once 'Crypt/TripleDES.php';
  1010. }
  1011. $symkey = substr($symkey, 0, 24);
  1012. $crypto = new Crypt_TripleDES();
  1013. break;
  1014. case 'DES-CBC':
  1015. if (!class_exists('Crypt_DES')) {
  1016. include_once 'Crypt/DES.php';
  1017. }
  1018. $crypto = new Crypt_DES();
  1019. break;
  1020. default:
  1021. return false;
  1022. }
  1023. $crypto->setKey($symkey);
  1024. $crypto->setIV($iv);
  1025. $decoded = $crypto->decrypt($ciphertext);
  1026. } else {
  1027. $decoded = $this->_extractBER($key);
  1028. }
  1029. if ($decoded !== false) {
  1030. $key = $decoded;
  1031. }
  1032. $components = array();
  1033. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1034. return false;
  1035. }
  1036. if ($this->_decodeLength($key) != strlen($key)) {
  1037. return false;
  1038. }
  1039. $tag = ord($this->_string_shift($key));
  1040. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1041. 0:d=0 hl=4 l= 631 cons: SEQUENCE
  1042. 4:d=1 hl=2 l= 1 prim: INTEGER :00
  1043. 7:d=1 hl=2 l= 13 cons: SEQUENCE
  1044. 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1045. 20:d=2 hl=2 l= 0 prim: NULL
  1046. 22:d=1 hl=4 l= 609 prim: OCTET STRING
  1047. ie. PKCS8 keys*/
  1048. if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
  1049. $this->_string_shift($key, 3);
  1050. $tag = CRYPT_RSA_ASN1_SEQUENCE;
  1051. }
  1052. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  1053. $temp = $this->_string_shift($key, $this->_decodeLength($key));
  1054. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT) {
  1055. return false;
  1056. }
  1057. $length = $this->_decodeLength($temp);
  1058. switch ($this->_string_shift($temp, $length)) {
  1059. case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption
  1060. break;
  1061. case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC
  1062. /*
  1063. PBEParameter ::= SEQUENCE {
  1064. salt OCTET STRING (SIZE(8)),
  1065. iterationCount INTEGER }
  1066. */
  1067. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1068. return false;
  1069. }
  1070. if ($this->_decodeLength($temp) != strlen($temp)) {
  1071. return false;
  1072. }
  1073. $this->_string_shift($temp); // assume it's an octet string
  1074. $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
  1075. if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER) {
  1076. return false;
  1077. }
  1078. $this->_decodeLength($temp);
  1079. list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
  1080. $this->_string_shift($key); // assume it's an octet string
  1081. $length = $this->_decodeLength($key);
  1082. if (strlen($key) != $length) {
  1083. return false;
  1084. }
  1085. if (!class_exists('Crypt_DES')) {
  1086. include_once 'Crypt/DES.php';
  1087. }
  1088. $crypto = new Crypt_DES();
  1089. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  1090. $key = $crypto->decrypt($key);
  1091. if ($key === false) {
  1092. return false;
  1093. }
  1094. return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
  1095. default:
  1096. return false;
  1097. }
  1098. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1099. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  1100. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  1101. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1102. 17:d=2 hl=2 l= 0 prim: NULL
  1103. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  1104. $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
  1105. $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
  1106. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  1107. // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
  1108. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  1109. if ($tag == CRYPT_RSA_ASN1_BITSTRING) {
  1110. $this->_string_shift($key);
  1111. }
  1112. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  1113. return false;
  1114. }
  1115. if ($this->_decodeLength($key) != strlen($key)) {
  1116. return false;
  1117. }
  1118. $tag = ord($this->_string_shift($key));
  1119. }
  1120. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  1121. return false;
  1122. }
  1123. $length = $this->_decodeLength($key);
  1124. $temp = $this->_string_shift($key, $length);
  1125. if (strlen($temp) != 1 || ord($temp) > 2) {
  1126. $components['modulus'] = new Math_BigInteger($temp, 256);
  1127. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  1128. $length = $this->_decodeLength($key);
  1129. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1130. return $components;
  1131. }
  1132. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  1133. return false;
  1134. }
  1135. $length = $this->_decodeLength($key);
  1136. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1137. $this->_string_shift($key);
  1138. $length = $this->_decodeLength($key);
  1139. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1140. $this->_string_shift($key);
  1141. $length = $this->_decodeLength($key);
  1142. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1143. $this->_string_shift($key);
  1144. $length = $this->_decodeLength($key);
  1145. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256));
  1146. $this->_string_shift($key);
  1147. $length = $this->_decodeLength($key);
  1148. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256);
  1149. $t

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