PageRenderTime 62ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/vendors/phpseclib/Crypt/RSA.php

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

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