PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/openemr/openemr
PHP | 3037 lines | 1627 code | 297 blank | 1113 comment | 266 complexity | e97a99b790eecd75f3fb5edb5cb6a951 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1

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

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

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