PageRenderTime 85ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/phpseclib/Crypt/RSA.php

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

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