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

/protected/vendors/phpseclib/Crypt/RSA.php

https://bitbucket.org/negge/tlklan2
PHP | 2640 lines | 1359 code | 264 blank | 1017 comment | 234 complexity | 7c652798aa015caffacdea7f5de94fce MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause, GPL-3.0

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

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

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