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

/application/library/PhpSecure/Crypt/RSA.php

https://github.com/liuhui244671426/yaf.app
PHP | 2672 lines | 1355 code | 270 blank | 1047 comment | 229 complexity | 6225e1c3a5268bdc12dfd37a0685cb42 MD5 | raw file

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

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

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