PageRenderTime 64ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/plugins/OStatus/extlib/phpseclib/Crypt/RSA.php

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

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