PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/phpseclib/Crypt/RSA.php

https://github.com/KenjiOhtsuka/core
PHP | 2941 lines | 1543 code | 293 blank | 1105 comment | 266 complexity | d6ab72dbefec0a5cddbc40625ff30616 MD5 | raw file

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

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