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

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

https://bitbucket.org/devthiagolino/gepro-sistema
PHP | 2810 lines | 1464 code | 282 blank | 1064 comment | 254 complexity | 84f991ad21aef7727148a0c108c402a1 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, CC-BY-3.0

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

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