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

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

https://bitbucket.org/openemr/openemr
PHP | 3037 lines | 1627 code | 297 blank | 1113 comment | 266 complexity | e97a99b790eecd75f3fb5edb5cb6a951 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0, GPL-2.0, LGPL-3.0, BSD-3-Clause, Unlicense, MPL-2.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  4. *
  5. * PHP version 5
  6. *
  7. * Here's an example of how to encrypt and decrypt text with this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * $rsa = new \phpseclib\Crypt\RSA();
  13. * extract($rsa->createKey());
  14. *
  15. * $plaintext = 'terrafrost';
  16. *
  17. * $rsa->loadKey($privatekey);
  18. * $ciphertext = $rsa->encrypt($plaintext);
  19. *
  20. * $rsa->loadKey($publickey);
  21. * echo $rsa->decrypt($ciphertext);
  22. * ?>
  23. * </code>
  24. *
  25. * Here's an example of how to create signatures and verify signatures with this library:
  26. * <code>
  27. * <?php
  28. * include 'vendor/autoload.php';
  29. *
  30. * $rsa = new \phpseclib\Crypt\RSA();
  31. * extract($rsa->createKey());
  32. *
  33. * $plaintext = 'terrafrost';
  34. *
  35. * $rsa->loadKey($privatekey);
  36. * $signature = $rsa->sign($plaintext);
  37. *
  38. * $rsa->loadKey($publickey);
  39. * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
  40. * ?>
  41. * </code>
  42. *
  43. * @category Crypt
  44. * @package RSA
  45. * @author Jim Wigginton <terrafrost@php.net>
  46. * @copyright 2009 Jim Wigginton
  47. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  48. * @link http://phpseclib.sourceforge.net
  49. */
  50. namespace phpseclib\Crypt;
  51. use phpseclib\Math\BigInteger;
  52. /**
  53. * Pure-PHP PKCS#1 compliant implementation of RSA.
  54. *
  55. * @package RSA
  56. * @author Jim Wigginton <terrafrost@php.net>
  57. * @access public
  58. */
  59. class RSA
  60. {
  61. /**#@+
  62. * @access public
  63. * @see self::encrypt()
  64. * @see self::decrypt()
  65. */
  66. /**
  67. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  68. * (OAEP) for encryption / decryption.
  69. *
  70. * Uses sha1 by default.
  71. *
  72. * @see self::setHash()
  73. * @see self::setMGFHash()
  74. */
  75. const ENCRYPTION_OAEP = 1;
  76. /**
  77. * Use PKCS#1 padding.
  78. *
  79. * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  80. * compatibility with protocols (like SSH-1) written before OAEP's introduction.
  81. */
  82. const ENCRYPTION_PKCS1 = 2;
  83. /**
  84. * Do not use any padding
  85. *
  86. * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
  87. * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
  88. */
  89. const ENCRYPTION_NONE = 3;
  90. /**#@-*/
  91. /**#@+
  92. * @access public
  93. * @see self::sign()
  94. * @see self::verify()
  95. * @see self::setHash()
  96. */
  97. /**
  98. * Use the Probabilistic Signature Scheme for signing
  99. *
  100. * Uses sha1 by default.
  101. *
  102. * @see self::setSaltLength()
  103. * @see self::setMGFHash()
  104. */
  105. const SIGNATURE_PSS = 1;
  106. /**
  107. * Use the PKCS#1 scheme by default.
  108. *
  109. * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  110. * compatibility with protocols (like SSH-2) written before PSS's introduction.
  111. */
  112. const SIGNATURE_PKCS1 = 2;
  113. /**#@-*/
  114. /**#@+
  115. * @access private
  116. * @see \phpseclib\Crypt\RSA::createKey()
  117. */
  118. /**
  119. * ASN1 Integer
  120. */
  121. const ASN1_INTEGER = 2;
  122. /**
  123. * ASN1 Bit String
  124. */
  125. const ASN1_BITSTRING = 3;
  126. /**
  127. * ASN1 Octet String
  128. */
  129. const ASN1_OCTETSTRING = 4;
  130. /**
  131. * ASN1 Object Identifier
  132. */
  133. const ASN1_OBJECT = 6;
  134. /**
  135. * ASN1 Sequence (with the constucted bit set)
  136. */
  137. const ASN1_SEQUENCE = 48;
  138. /**#@-*/
  139. /**#@+
  140. * @access private
  141. * @see \phpseclib\Crypt\RSA::__construct()
  142. */
  143. /**
  144. * To use the pure-PHP implementation
  145. */
  146. const MODE_INTERNAL = 1;
  147. /**
  148. * To use the OpenSSL library
  149. *
  150. * (if enabled; otherwise, the internal implementation will be used)
  151. */
  152. const MODE_OPENSSL = 2;
  153. /**#@-*/
  154. /**#@+
  155. * @access public
  156. * @see \phpseclib\Crypt\RSA::createKey()
  157. * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat()
  158. */
  159. /**
  160. * PKCS#1 formatted private key
  161. *
  162. * Used by OpenSSH
  163. */
  164. const PRIVATE_FORMAT_PKCS1 = 0;
  165. /**
  166. * PuTTY formatted private key
  167. */
  168. const PRIVATE_FORMAT_PUTTY = 1;
  169. /**
  170. * XML formatted private key
  171. */
  172. const PRIVATE_FORMAT_XML = 2;
  173. /**
  174. * PKCS#8 formatted private key
  175. */
  176. const PRIVATE_FORMAT_PKCS8 = 8;
  177. /**#@-*/
  178. /**#@+
  179. * @access public
  180. * @see \phpseclib\Crypt\RSA::createKey()
  181. * @see \phpseclib\Crypt\RSA::setPublicKeyFormat()
  182. */
  183. /**
  184. * Raw public key
  185. *
  186. * An array containing two \phpseclib\Math\BigInteger objects.
  187. *
  188. * The exponent can be indexed with any of the following:
  189. *
  190. * 0, e, exponent, publicExponent
  191. *
  192. * The modulus can be indexed with any of the following:
  193. *
  194. * 1, n, modulo, modulus
  195. */
  196. const PUBLIC_FORMAT_RAW = 3;
  197. /**
  198. * PKCS#1 formatted public key (raw)
  199. *
  200. * Used by File/X509.php
  201. *
  202. * Has the following header:
  203. *
  204. * -----BEGIN RSA PUBLIC KEY-----
  205. *
  206. * Analogous to ssh-keygen's pem format (as specified by -m)
  207. */
  208. const PUBLIC_FORMAT_PKCS1 = 4;
  209. const PUBLIC_FORMAT_PKCS1_RAW = 4;
  210. /**
  211. * XML formatted public key
  212. */
  213. const PUBLIC_FORMAT_XML = 5;
  214. /**
  215. * OpenSSH formatted public key
  216. *
  217. * Place in $HOME/.ssh/authorized_keys
  218. */
  219. const PUBLIC_FORMAT_OPENSSH = 6;
  220. /**
  221. * PKCS#1 formatted public key (encapsulated)
  222. *
  223. * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set)
  224. *
  225. * Has the following header:
  226. *
  227. * -----BEGIN PUBLIC KEY-----
  228. *
  229. * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8
  230. * is specific to private keys it's basically creating a DER-encoded wrapper
  231. * for keys. This just extends that same concept to public keys (much like ssh-keygen)
  232. */
  233. const PUBLIC_FORMAT_PKCS8 = 7;
  234. /**#@-*/
  235. /**
  236. * Precomputed Zero
  237. *
  238. * @var array
  239. * @access private
  240. */
  241. var $zero;
  242. /**
  243. * Precomputed One
  244. *
  245. * @var array
  246. * @access private
  247. */
  248. var $one;
  249. /**
  250. * Private Key Format
  251. *
  252. * @var int
  253. * @access private
  254. */
  255. var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1;
  256. /**
  257. * Public Key Format
  258. *
  259. * @var int
  260. * @access public
  261. */
  262. var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8;
  263. /**
  264. * Modulus (ie. n)
  265. *
  266. * @var \phpseclib\Math\BigInteger
  267. * @access private
  268. */
  269. var $modulus;
  270. /**
  271. * Modulus length
  272. *
  273. * @var \phpseclib\Math\BigInteger
  274. * @access private
  275. */
  276. var $k;
  277. /**
  278. * Exponent (ie. e or d)
  279. *
  280. * @var \phpseclib\Math\BigInteger
  281. * @access private
  282. */
  283. var $exponent;
  284. /**
  285. * Primes for Chinese Remainder Theorem (ie. p and q)
  286. *
  287. * @var array
  288. * @access private
  289. */
  290. var $primes;
  291. /**
  292. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  293. *
  294. * @var array
  295. * @access private
  296. */
  297. var $exponents;
  298. /**
  299. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  300. *
  301. * @var array
  302. * @access private
  303. */
  304. var $coefficients;
  305. /**
  306. * Hash name
  307. *
  308. * @var string
  309. * @access private
  310. */
  311. var $hashName;
  312. /**
  313. * Hash function
  314. *
  315. * @var \phpseclib\Crypt\Hash
  316. * @access private
  317. */
  318. var $hash;
  319. /**
  320. * Length of hash function output
  321. *
  322. * @var int
  323. * @access private
  324. */
  325. var $hLen;
  326. /**
  327. * Length of salt
  328. *
  329. * @var int
  330. * @access private
  331. */
  332. var $sLen;
  333. /**
  334. * Hash function for the Mask Generation Function
  335. *
  336. * @var \phpseclib\Crypt\Hash
  337. * @access private
  338. */
  339. var $mgfHash;
  340. /**
  341. * Length of MGF hash function output
  342. *
  343. * @var int
  344. * @access private
  345. */
  346. var $mgfHLen;
  347. /**
  348. * Encryption mode
  349. *
  350. * @var int
  351. * @access private
  352. */
  353. var $encryptionMode = self::ENCRYPTION_OAEP;
  354. /**
  355. * Signature mode
  356. *
  357. * @var int
  358. * @access private
  359. */
  360. var $signatureMode = self::SIGNATURE_PSS;
  361. /**
  362. * Public Exponent
  363. *
  364. * @var mixed
  365. * @access private
  366. */
  367. var $publicExponent = false;
  368. /**
  369. * Password
  370. *
  371. * @var string
  372. * @access private
  373. */
  374. var $password = false;
  375. /**
  376. * Components
  377. *
  378. * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
  379. * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
  380. *
  381. * @see self::_start_element_handler()
  382. * @var array
  383. * @access private
  384. */
  385. var $components = array();
  386. /**
  387. * Current String
  388. *
  389. * For use with parsing XML formatted keys.
  390. *
  391. * @see self::_character_handler()
  392. * @see self::_stop_element_handler()
  393. * @var mixed
  394. * @access private
  395. */
  396. var $current;
  397. /**
  398. * OpenSSL configuration file name.
  399. *
  400. * Set to null to use system configuration file.
  401. * @see self::createKey()
  402. * @var mixed
  403. * @Access public
  404. */
  405. var $configFile;
  406. /**
  407. * Public key comment field.
  408. *
  409. * @var string
  410. * @access private
  411. */
  412. var $comment = 'phpseclib-generated-key';
  413. /**
  414. * The constructor
  415. *
  416. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  417. * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  418. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  419. *
  420. * @return \phpseclib\Crypt\RSA
  421. * @access public
  422. */
  423. function __construct()
  424. {
  425. $this->configFile = dirname(__FILE__) . '/../openssl.cnf';
  426. if (!defined('CRYPT_RSA_MODE')) {
  427. switch (true) {
  428. // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
  429. // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
  430. // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
  431. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
  432. define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
  433. break;
  434. case extension_loaded('openssl') && file_exists($this->configFile):
  435. // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
  436. ob_start();
  437. @phpinfo();
  438. $content = ob_get_contents();
  439. ob_end_clean();
  440. preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
  441. $versions = array();
  442. if (!empty($matches[1])) {
  443. for ($i = 0; $i < count($matches[1]); $i++) {
  444. $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
  445. // Remove letter part in OpenSSL version
  446. if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) {
  447. $versions[$matches[1][$i]] = $fullVersion;
  448. } else {
  449. $versions[$matches[1][$i]] = $m[0];
  450. }
  451. }
  452. }
  453. // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
  454. switch (true) {
  455. case !isset($versions['Header']):
  456. case !isset($versions['Library']):
  457. case $versions['Header'] == $versions['Library']:
  458. define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
  459. break;
  460. default:
  461. define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
  462. define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
  463. }
  464. break;
  465. default:
  466. define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
  467. }
  468. }
  469. $this->zero = new BigInteger();
  470. $this->one = new BigInteger(1);
  471. $this->hash = new Hash('sha1');
  472. $this->hLen = $this->hash->getLength();
  473. $this->hashName = 'sha1';
  474. $this->mgfHash = new Hash('sha1');
  475. $this->mgfHLen = $this->mgfHash->getLength();
  476. }
  477. /**
  478. * Create public / private key pair
  479. *
  480. * Returns an array with the following three elements:
  481. * - 'privatekey': The private key.
  482. * - 'publickey': The public key.
  483. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  484. * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.
  485. *
  486. * @access public
  487. * @param int $bits
  488. * @param int $timeout
  489. * @param array $p
  490. */
  491. function createKey($bits = 1024, $timeout = false, $partial = array())
  492. {
  493. if (!defined('CRYPT_RSA_EXPONENT')) {
  494. // http://en.wikipedia.org/wiki/65537_%28number%29
  495. define('CRYPT_RSA_EXPONENT', '65537');
  496. }
  497. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  498. // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
  499. // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
  500. // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then
  501. // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
  502. // generation when there's a chance neither gmp nor OpenSSL are installed)
  503. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  504. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  505. }
  506. // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  507. if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
  508. $config = array();
  509. if (isset($this->configFile)) {
  510. $config['config'] = $this->configFile;
  511. }
  512. $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
  513. openssl_pkey_export($rsa, $privatekey, null, $config);
  514. $publickey = openssl_pkey_get_details($rsa);
  515. $publickey = $publickey['key'];
  516. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1)));
  517. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1)));
  518. // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  519. while (openssl_error_string() !== false) {
  520. }
  521. return array(
  522. 'privatekey' => $privatekey,
  523. 'publickey' => $publickey,
  524. 'partialkey' => false
  525. );
  526. }
  527. static $e;
  528. if (!isset($e)) {
  529. $e = new BigInteger(CRYPT_RSA_EXPONENT);
  530. }
  531. extract($this->_generateMinMax($bits));
  532. $absoluteMin = $min;
  533. $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
  534. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  535. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  536. $temp = CRYPT_RSA_SMALLEST_PRIME;
  537. } else {
  538. $num_primes = 2;
  539. }
  540. extract($this->_generateMinMax($temp + $bits % $temp));
  541. $finalMax = $max;
  542. extract($this->_generateMinMax($temp));
  543. $generator = new BigInteger();
  544. $n = $this->one->copy();
  545. if (!empty($partial)) {
  546. extract(unserialize($partial));
  547. } else {
  548. $exponents = $coefficients = $primes = array();
  549. $lcm = array(
  550. 'top' => $this->one->copy(),
  551. 'bottom' => false
  552. );
  553. }
  554. $start = time();
  555. $i0 = count($primes) + 1;
  556. do {
  557. for ($i = $i0; $i <= $num_primes; $i++) {
  558. if ($timeout !== false) {
  559. $timeout-= time() - $start;
  560. $start = time();
  561. if ($timeout <= 0) {
  562. return array(
  563. 'privatekey' => '',
  564. 'publickey' => '',
  565. 'partialkey' => serialize(array(
  566. 'primes' => $primes,
  567. 'coefficients' => $coefficients,
  568. 'lcm' => $lcm,
  569. 'exponents' => $exponents
  570. ))
  571. );
  572. }
  573. }
  574. if ($i == $num_primes) {
  575. list($min, $temp) = $absoluteMin->divide($n);
  576. if (!$temp->equals($this->zero)) {
  577. $min = $min->add($this->one); // ie. ceil()
  578. }
  579. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  580. } else {
  581. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  582. }
  583. if ($primes[$i] === false) { // if we've reached the timeout
  584. if (count($primes) > 1) {
  585. $partialkey = '';
  586. } else {
  587. array_pop($primes);
  588. $partialkey = serialize(array(
  589. 'primes' => $primes,
  590. 'coefficients' => $coefficients,
  591. 'lcm' => $lcm,
  592. 'exponents' => $exponents
  593. ));
  594. }
  595. return array(
  596. 'privatekey' => '',
  597. 'publickey' => '',
  598. 'partialkey' => $partialkey
  599. );
  600. }
  601. // the first coefficient is calculated differently from the rest
  602. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  603. if ($i > 2) {
  604. $coefficients[$i] = $n->modInverse($primes[$i]);
  605. }
  606. $n = $n->multiply($primes[$i]);
  607. $temp = $primes[$i]->subtract($this->one);
  608. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  609. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  610. $lcm['top'] = $lcm['top']->multiply($temp);
  611. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  612. $exponents[$i] = $e->modInverse($temp);
  613. }
  614. list($temp) = $lcm['top']->divide($lcm['bottom']);
  615. $gcd = $temp->gcd($e);
  616. $i0 = 1;
  617. } while (!$gcd->equals($this->one));
  618. $d = $e->modInverse($temp);
  619. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  620. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  621. // RSAPrivateKey ::= SEQUENCE {
  622. // version Version,
  623. // modulus INTEGER, -- n
  624. // publicExponent INTEGER, -- e
  625. // privateExponent INTEGER, -- d
  626. // prime1 INTEGER, -- p
  627. // prime2 INTEGER, -- q
  628. // exponent1 INTEGER, -- d mod (p-1)
  629. // exponent2 INTEGER, -- d mod (q-1)
  630. // coefficient INTEGER, -- (inverse of q) mod p
  631. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  632. // }
  633. return array(
  634. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  635. 'publickey' => $this->_convertPublicKey($n, $e),
  636. 'partialkey' => false
  637. );
  638. }
  639. /**
  640. * Convert a private key to the appropriate format.
  641. *
  642. * @access private
  643. * @see self::setPrivateKeyFormat()
  644. * @param string $RSAPrivateKey
  645. * @return string
  646. */
  647. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  648. {
  649. $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML;
  650. $num_primes = count($primes);
  651. $raw = array(
  652. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  653. 'modulus' => $n->toBytes($signed),
  654. 'publicExponent' => $e->toBytes($signed),
  655. 'privateExponent' => $d->toBytes($signed),
  656. 'prime1' => $primes[1]->toBytes($signed),
  657. 'prime2' => $primes[2]->toBytes($signed),
  658. 'exponent1' => $exponents[1]->toBytes($signed),
  659. 'exponent2' => $exponents[2]->toBytes($signed),
  660. 'coefficient' => $coefficients[2]->toBytes($signed)
  661. );
  662. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  663. // call _convertPublicKey() instead.
  664. switch ($this->privateKeyFormat) {
  665. case self::PRIVATE_FORMAT_XML:
  666. if ($num_primes != 2) {
  667. return false;
  668. }
  669. return "<RSAKeyValue>\r\n" .
  670. ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
  671. ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
  672. ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
  673. ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
  674. ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
  675. ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
  676. ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
  677. ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
  678. '</RSAKeyValue>';
  679. break;
  680. case self::PRIVATE_FORMAT_PUTTY:
  681. if ($num_primes != 2) {
  682. return false;
  683. }
  684. $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
  685. $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
  686. $key.= $encryption;
  687. $key.= "\r\nComment: " . $this->comment . "\r\n";
  688. $public = pack(
  689. 'Na*Na*Na*',
  690. strlen('ssh-rsa'),
  691. 'ssh-rsa',
  692. strlen($raw['publicExponent']),
  693. $raw['publicExponent'],
  694. strlen($raw['modulus']),
  695. $raw['modulus']
  696. );
  697. $source = pack(
  698. 'Na*Na*Na*Na*',
  699. strlen('ssh-rsa'),
  700. 'ssh-rsa',
  701. strlen($encryption),
  702. $encryption,
  703. strlen($this->comment),
  704. $this->comment,
  705. strlen($public),
  706. $public
  707. );
  708. $public = base64_encode($public);
  709. $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
  710. $key.= chunk_split($public, 64);
  711. $private = pack(
  712. 'Na*Na*Na*Na*',
  713. strlen($raw['privateExponent']),
  714. $raw['privateExponent'],
  715. strlen($raw['prime1']),
  716. $raw['prime1'],
  717. strlen($raw['prime2']),
  718. $raw['prime2'],
  719. strlen($raw['coefficient']),
  720. $raw['coefficient']
  721. );
  722. if (empty($this->password) && !is_string($this->password)) {
  723. $source.= pack('Na*', strlen($private), $private);
  724. $hashkey = 'putty-private-key-file-mac-key';
  725. } else {
  726. $private.= Random::string(16 - (strlen($private) & 15));
  727. $source.= pack('Na*', strlen($private), $private);
  728. $sequence = 0;
  729. $symkey = '';
  730. while (strlen($symkey) < 32) {
  731. $temp = pack('Na*', $sequence++, $this->password);
  732. $symkey.= pack('H*', sha1($temp));
  733. }
  734. $symkey = substr($symkey, 0, 32);
  735. $crypto = new AES();
  736. $crypto->setKey($symkey);
  737. $crypto->disablePadding();
  738. $private = $crypto->encrypt($private);
  739. $hashkey = 'putty-private-key-file-mac-key' . $this->password;
  740. }
  741. $private = base64_encode($private);
  742. $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
  743. $key.= chunk_split($private, 64);
  744. $hash = new Hash('sha1');
  745. $hash->setKey(pack('H*', sha1($hashkey)));
  746. $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
  747. return $key;
  748. default: // eg. self::PRIVATE_FORMAT_PKCS1
  749. $components = array();
  750. foreach ($raw as $name => $value) {
  751. $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  752. }
  753. $RSAPrivateKey = implode('', $components);
  754. if ($num_primes > 2) {
  755. $OtherPrimeInfos = '';
  756. for ($i = 3; $i <= $num_primes; $i++) {
  757. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  758. //
  759. // OtherPrimeInfo ::= SEQUENCE {
  760. // prime INTEGER, -- ri
  761. // exponent INTEGER, -- di
  762. // coefficient INTEGER -- ti
  763. // }
  764. $OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  765. $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  766. $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  767. $OtherPrimeInfos.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  768. }
  769. $RSAPrivateKey.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  770. }
  771. $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  772. if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) {
  773. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  774. $RSAPrivateKey = pack(
  775. 'Ca*a*Ca*a*',
  776. self::ASN1_INTEGER,
  777. "\01\00",
  778. $rsaOID,
  779. 4,
  780. $this->_encodeLength(strlen($RSAPrivateKey)),
  781. $RSAPrivateKey
  782. );
  783. $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  784. if (!empty($this->password) || is_string($this->password)) {
  785. $salt = Random::string(8);
  786. $iterationCount = 2048;
  787. $crypto = new DES();
  788. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  789. $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
  790. $parameters = pack(
  791. 'Ca*a*Ca*N',
  792. self::ASN1_OCTETSTRING,
  793. $this->_encodeLength(strlen($salt)),
  794. $salt,
  795. self::ASN1_INTEGER,
  796. $this->_encodeLength(4),
  797. $iterationCount
  798. );
  799. $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
  800. $encryptionAlgorithm = pack(
  801. 'Ca*a*Ca*a*',
  802. self::ASN1_OBJECT,
  803. $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)),
  804. $pbeWithMD5AndDES_CBC,
  805. self::ASN1_SEQUENCE,
  806. $this->_encodeLength(strlen($parameters)),
  807. $parameters
  808. );
  809. $RSAPrivateKey = pack(
  810. 'Ca*a*Ca*a*',
  811. self::ASN1_SEQUENCE,
  812. $this->_encodeLength(strlen($encryptionAlgorithm)),
  813. $encryptionAlgorithm,
  814. self::ASN1_OCTETSTRING,
  815. $this->_encodeLength(strlen($RSAPrivateKey)),
  816. $RSAPrivateKey
  817. );
  818. $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  819. $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" .
  820. chunk_split(base64_encode($RSAPrivateKey), 64) .
  821. '-----END ENCRYPTED PRIVATE KEY-----';
  822. } else {
  823. $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" .
  824. chunk_split(base64_encode($RSAPrivateKey), 64) .
  825. '-----END PRIVATE KEY-----';
  826. }
  827. return $RSAPrivateKey;
  828. }
  829. if (!empty($this->password) || is_string($this->password)) {
  830. $iv = Random::string(8);
  831. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  832. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  833. $des = new TripleDES();
  834. $des->setKey($symkey);
  835. $des->setIV($iv);
  836. $iv = strtoupper(bin2hex($iv));
  837. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  838. "Proc-Type: 4,ENCRYPTED\r\n" .
  839. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  840. "\r\n" .
  841. chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
  842. '-----END RSA PRIVATE KEY-----';
  843. } else {
  844. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  845. chunk_split(base64_encode($RSAPrivateKey), 64) .
  846. '-----END RSA PRIVATE KEY-----';
  847. }
  848. return $RSAPrivateKey;
  849. }
  850. }
  851. /**
  852. * Convert a public key to the appropriate format
  853. *
  854. * @access private
  855. * @see self::setPublicKeyFormat()
  856. * @param string $RSAPrivateKey
  857. * @return string
  858. */
  859. function _convertPublicKey($n, $e)
  860. {
  861. $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML;
  862. $modulus = $n->toBytes($signed);
  863. $publicExponent = $e->toBytes($signed);
  864. switch ($this->publicKeyFormat) {
  865. case self::PUBLIC_FORMAT_RAW:
  866. return array('e' => $e->copy(), 'n' => $n->copy());
  867. case self::PUBLIC_FORMAT_XML:
  868. return "<RSAKeyValue>\r\n" .
  869. ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
  870. ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
  871. '</RSAKeyValue>';
  872. break;
  873. case self::PUBLIC_FORMAT_OPENSSH:
  874. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  875. // string "ssh-rsa"
  876. // mpint e
  877. // mpint n
  878. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  879. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
  880. return $RSAPublicKey;
  881. default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1
  882. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  883. // RSAPublicKey ::= SEQUENCE {
  884. // modulus INTEGER, -- n
  885. // publicExponent INTEGER -- e
  886. // }
  887. $components = array(
  888. 'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  889. 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  890. );
  891. $RSAPublicKey = pack(
  892. 'Ca*a*a*',
  893. self::ASN1_SEQUENCE,
  894. $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  895. $components['modulus'],
  896. $components['publicExponent']
  897. );
  898. if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) {
  899. $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
  900. chunk_split(base64_encode($RSAPublicKey), 64) .
  901. '-----END RSA PUBLIC KEY-----';
  902. } else {
  903. // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
  904. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  905. $RSAPublicKey = chr(0) . $RSAPublicKey;
  906. $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  907. $RSAPublicKey = pack(
  908. 'Ca*a*',
  909. self::ASN1_SEQUENCE,
  910. $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
  911. $rsaOID . $RSAPublicKey
  912. );
  913. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  914. chunk_split(base64_encode($RSAPublicKey), 64) .
  915. '-----END PUBLIC KEY-----';
  916. }
  917. return $RSAPublicKey;
  918. }
  919. }
  920. /**
  921. * Break a public or private key down into its constituant components
  922. *
  923. * @access private
  924. * @see self::_convertPublicKey()
  925. * @see self::_convertPrivateKey()
  926. * @param string $key
  927. * @param int $type
  928. * @return array
  929. */
  930. function _parseKey($key, $type)
  931. {
  932. if ($type != self::PUBLIC_FORMAT_RAW && !is_string($key)) {
  933. return false;
  934. }
  935. switch ($type) {
  936. case self::PUBLIC_FORMAT_RAW:
  937. if (!is_array($key)) {
  938. return false;
  939. }
  940. $components = array();
  941. switch (true) {
  942. case isset($key['e']):
  943. $components['publicExponent'] = $key['e']->copy();
  944. break;
  945. case isset($key['exponent']):
  946. $components['publicExponent'] = $key['exponent']->copy();
  947. break;
  948. case isset($key['publicExponent']):
  949. $components['publicExponent'] = $key['publicExponent']->copy();
  950. break;
  951. case isset($key[0]):
  952. $components['publicExponent'] = $key[0]->copy();
  953. }
  954. switch (true) {
  955. case isset($key['n']):
  956. $components['modulus'] = $key['n']->copy();
  957. break;
  958. case isset($key['modulo']):
  959. $components['modulus'] = $key['modulo']->copy();
  960. break;
  961. case isset($key['modulus']):
  962. $components['modulus'] = $key['modulus']->copy();
  963. break;
  964. case isset($key[1]):
  965. $components['modulus'] = $key[1]->copy();
  966. }
  967. return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
  968. case self::PRIVATE_FORMAT_PKCS1:
  969. case self::PRIVATE_FORMAT_PKCS8:
  970. case self::PUBLIC_FORMAT_PKCS1:
  971. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  972. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  973. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  974. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  975. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  976. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  977. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  978. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  979. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  980. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  981. implementation are part of the standard, as well.
  982. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  983. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  984. $iv = pack('H*', trim($matches[2]));
  985. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  986. $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
  987. // remove the Proc-Type / DEK-Info sections as they're no longer needed
  988. $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
  989. $ciphertext = $this->_extractBER($key);
  990. if ($ciphertext === false) {
  991. $ciphertext = $key;
  992. }
  993. switch ($matches[1]) {
  994. case 'AES-256-CBC':
  995. $crypto = new AES();
  996. break;
  997. case 'AES-128-CBC':
  998. $symkey = substr($symkey, 0, 16);
  999. $crypto = new AES();
  1000. break;
  1001. case 'DES-EDE3-CFB':
  1002. $crypto = new TripleDES(Base::MODE_CFB);
  1003. break;
  1004. case 'DES-EDE3-CBC':
  1005. $symkey = substr($symkey, 0, 24);
  1006. $crypto = new TripleDES();
  1007. break;
  1008. case 'DES-CBC':
  1009. $crypto = new DES();
  1010. break;
  1011. default:
  1012. return false;
  1013. }
  1014. $crypto->setKey($symkey);
  1015. $crypto->setIV($iv);
  1016. $decoded = $crypto->decrypt($ciphertext);
  1017. } else {
  1018. $decoded = $this->_extractBER($key);
  1019. }
  1020. if ($decoded !== false) {
  1021. $key = $decoded;
  1022. }
  1023. $components = array();
  1024. if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
  1025. return false;
  1026. }
  1027. if ($this->_decodeLength($key) != strlen($key)) {
  1028. return false;
  1029. }
  1030. $tag = ord($this->_string_shift($key));
  1031. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1032. 0:d=0 hl=4 l= 631 cons: SEQUENCE
  1033. 4:d=1 hl=2 l= 1 prim: INTEGER :00
  1034. 7:d=1 hl=2 l= 13 cons: SEQUENCE
  1035. 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1036. 20:d=2 hl=2 l= 0 prim: NULL
  1037. 22:d=1 hl=4 l= 609 prim: OCTET STRING
  1038. ie. PKCS8 keys*/
  1039. if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") {
  1040. $this->_string_shift($key, 3);
  1041. $tag = self::ASN1_SEQUENCE;
  1042. }
  1043. if ($tag == self::ASN1_SEQUENCE) {
  1044. $temp = $this->_string_shift($key, $this->_decodeLength($key));
  1045. if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) {
  1046. return false;
  1047. }
  1048. $length = $this->_decodeLength($temp);
  1049. switch ($this->_string_shift($temp, $length)) {
  1050. case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption
  1051. break;
  1052. case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC
  1053. /*
  1054. PBEParameter ::= SEQUENCE {
  1055. salt OCTET STRING (SIZE(8)),
  1056. iterationCount INTEGER }
  1057. */
  1058. if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) {
  1059. return false;
  1060. }
  1061. if ($this->_decodeLength($temp) != strlen($temp)) {
  1062. return false;
  1063. }
  1064. $this->_string_shift($temp); // assume it's an octet string
  1065. $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
  1066. if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) {
  1067. return false;
  1068. }
  1069. $this->_decodeLength($temp);
  1070. list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
  1071. $this->_string_shift($key); // assume it's an octet string
  1072. $length = $this->_decodeLength($key);
  1073. if (strlen($key) != $length) {
  1074. return false;
  1075. }
  1076. $crypto = new DES();
  1077. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  1078. $key = $crypto->decrypt($key);
  1079. if ($key === false) {
  1080. return false;
  1081. }
  1082. return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1);
  1083. default:
  1084. return false;
  1085. }
  1086. /* intended for keys for which OpenSSL's asn1parse returns the following:
  1087. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  1088. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  1089. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  1090. 17:d=2 hl=2 l= 0 prim: NULL
  1091. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  1092. $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
  1093. $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
  1094. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  1095. // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
  1096. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  1097. if ($tag == self::ASN1_BITSTRING) {
  1098. $this->_string_shift($key);
  1099. }
  1100. if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
  1101. return false;
  1102. }
  1103. if ($this->_decodeLength($key) != strlen($key)) {
  1104. return false;
  1105. }
  1106. $tag = ord($this->_string_shift($key));
  1107. }
  1108. if ($tag != self::ASN1_INTEGER) {
  1109. return false;
  1110. }
  1111. $length = $this->_decodeLength($key);
  1112. $temp = $this->_string_shift($key, $length);
  1113. if (strlen($temp) != 1 || ord($temp) > 2) {
  1114. $components['modulus'] = new BigInteger($temp, 256);
  1115. $this->_string_shift($key); // skip over self::ASN1_INTEGER
  1116. $length = $this->_decodeLength($key);
  1117. $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
  1118. return $components;
  1119. }
  1120. if (ord($this->_string_shift($key)) != self::ASN1_INTEGER) {
  1121. return false;
  1122. }
  1123. $length = $this->_decodeLength($key);
  1124. $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256);
  1125. $this->_string_shift($key);
  1126. $length = $this->_decodeLength($key);
  1127. $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
  1128. $this->_string_shift($key);
  1129. $length = $this->_decodeLength($key);
  1130. $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256);
  1131. $this->_string_shift($key);
  1132. $length = $this->_decodeLength($key);
  1133. $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
  1134. $this->_string_shift($key);
  1135. $length = $this->_decodeLength($key);
  1136. $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
  1137. $this->_string_shift($key);
  1138. $length = $this->_decodeLength($key);
  1139. $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256));
  1140. $this->_string_shift($key);
  1141. $length = $this->_decodeLength($key);
  1142. $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
  1143. $this->_string_shift($key);
  1144. $length = $this->_decodeLength($key);
  1145. $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256));
  1146. if (!empty($key)) {
  1147. if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
  1148. return false;
  1149. }
  1150. $this->_decodeLength($key);
  1151. while (!empty($key)) {
  1152. if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) {
  1153. return false;
  1154. }
  1155. $this->_decodeLength($key);
  1156. $key = substr($key, 1);
  1157. $length = $this->_decodeLength($key);
  1158. $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256);
  1159. $this->_string_shift($key);
  1160. $length = $this->_decodeLength($key);
  1161. $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256);
  1162. $this->_string_shift($key);
  1163. $length = $this->_decodeLength($key);
  1164. $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256);
  1165. }
  1166. }
  1167. return $components;
  1168. case self::PUBLIC_FORMAT_OPENSSH:
  1169. $parts = explode(' ', $key, 3);
  1170. $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
  1171. if ($key === false) {
  1172. return false;
  1173. }
  1174. $comment = isset($parts[2]) ? $parts[2] : false;
  1175. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  1176. if (strlen($key) <= 4) {
  1177. return false;
  1178. }
  1179. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1180. $publicExponent = new BigInteger($this->_string_shift($key, $length), -256);
  1181. if (strlen($key) <= 4) {
  1182. return false;
  1183. }
  1184. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1185. $modulus = new BigInteger($this->_string_shift($key, $length), -256);
  1186. if ($cleanup && strlen($key)) {
  1187. if (strlen($key) <= 4) {
  1188. return false;
  1189. }
  1190. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  1191. $realModulus = new BigInteger($this->_string_shift($key, $length), -256);
  1192. return strlen($key) ? false : array(
  1193. 'modulus' => $realModulus,
  1194. 'publicExponent' => $modulus,
  1195. 'comment' => $comment
  1196. );
  1197. } else {
  1198. return strlen($key) ? false : array(
  1199. 'modulus' => $modulus,
  1200. 'publicExponent' => $publicExponent,
  1201. 'comment' => $comment
  1202. );
  1203. }
  1204. // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
  1205. // http://en.wikipedia.org/wiki/XML_Signature
  1206. case self::PRIVATE_FORMAT_XML:
  1207. case self::PUBLIC_FORMAT_XML:
  1208. $this->components = array();
  1209. $xml = xml_parser_create('UTF-8');
  1210. xml_set_object($xml, $this);
  1211. xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
  1212. xml_set_character_data_handler($xml, '_data_handler');
  1213. // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
  1214. if (!xml_parse($xml, '<xml>' . $key . '</xml>')) {
  1215. return false;
  1216. }
  1217. return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
  1218. // from PuTTY's SSHPUBK.C
  1219. case self::PRIVATE_FORMAT_PUTTY:
  1220. $components = array();
  1221. $key = preg_split('#\r\n|\r|\n#', $key);
  1222. $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
  1223. if ($type != 'ssh-rsa') {
  1224. return false;
  1225. }
  1226. $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
  1227. $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
  1228. $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
  1229. $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
  1230. $public = substr($public, 11);
  1231. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1232. $components['publicExponent'] = new BigInteger($this->_string_shift($public, $length), -256);
  1233. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  1234. $components['modulus'] = new BigInteger($this->_string_shift($public, $length), -256);
  1235. $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
  1236. $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
  1237. switch ($encryption) {
  1238. case 'aes256-cbc':
  1239. $symkey = '';
  1240. $sequence = 0;
  1241. while (strlen($symkey) < 32) {
  1242. $temp = pack('Na*', $sequence++, $this->password);
  1243. $symkey.= pack('H*', sha1($temp));
  1244. }
  1245. $symkey = substr($symkey, 0, 32);
  1246. $crypto = new AES();
  1247. }
  1248. if ($encryption != 'none') {
  1249. $crypto->setKey($symkey);
  1250. $crypto->disablePadding();
  1251. $private = $crypto->decrypt($private);
  1252. if ($private === false) {
  1253. return false;
  1254. }
  1255. }
  1256. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1257. if (strlen($private) < $length) {
  1258. return false;
  1259. }
  1260. $components['privateExponent'] = new BigInteger($this->_string_shift($private, $length), -256);
  1261. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1262. if (strlen($private) < $length) {
  1263. return false;
  1264. }
  1265. $components['primes'] = array(1 => new BigInteger($this->_string_shift($private, $length), -256));
  1266. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1267. if (strlen($private) < $length) {
  1268. return false;
  1269. }
  1270. $components['primes'][] = new BigInteger($this->_string_shift($private, $length), -256);
  1271. $temp = $components['primes'][1]->subtract($this->one);
  1272. $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
  1273. $temp = $components['primes'][2]->subtract($this->one);
  1274. $components['exponents'][] = $components['publicExponent']->modInverse($temp);
  1275. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1276. if (strlen($private) < $length) {
  1277. return false;
  1278. }
  1279. $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($private, $length), -256));
  1280. return $components;
  1281. }
  1282. }
  1283. /**
  1284. * Returns the key size
  1285. *
  1286. * More specifically, this returns the size of the modulo in bits.
  1287. *
  1288. * @access public
  1289. * @return int
  1290. */
  1291. function getSize()
  1292. {
  1293. return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
  1294. }
  1295. /**
  1296. * Start Element Handler
  1297. *
  1298. * Called by xml_set_element_handler()
  1299. *
  1300. * @access private
  1301. * @param resource $parser
  1302. * @param string $name
  1303. * @param array $attribs
  1304. */
  1305. function _start_element_handler($parser, $name, $attribs)
  1306. {
  1307. //$name = strtoupper($name);
  1308. switch ($name) {
  1309. case 'MODULUS':
  1310. $this->current = &$this->components['modulus'];
  1311. break;
  1312. case 'EXPONENT':
  1313. $this->current = &$this->components['publicExponent'];
  1314. break;
  1315. case 'P':
  1316. $this->current = &$this->components['primes'][1];
  1317. break;
  1318. case 'Q':
  1319. $this->current = &$this->components['primes'][2];
  1320. break;
  1321. case 'DP':
  1322. $this->current = &$this->components['exponents'][1];
  1323. break;
  1324. case 'DQ':
  1325. $this->current = &$this->components['exponents'][2];
  1326. break;
  1327. case 'INVERSEQ':
  1328. $this->current = &$this->components['coefficients'][2];
  1329. break;
  1330. case 'D':
  1331. $this->current = &$this->components['privateExponent'];
  1332. }
  1333. $this->current = '';
  1334. }
  1335. /**
  1336. * Stop Element Handler
  1337. *
  1338. * Called by xml_set_element_handler()
  1339. *
  1340. * @access private
  1341. * @param resource $parser
  1342. * @param string $name
  1343. */
  1344. function _stop_element_handler($parser, $name)
  1345. {
  1346. if (isset($this->current)) {
  1347. $this->current = new BigInteger(base64_decode($this->current), 256);
  1348. unset($this->current);
  1349. }
  1350. }
  1351. /**
  1352. * Data Handler
  1353. *
  1354. * Called by xml_set_character_data_handler()
  1355. *
  1356. * @access private
  1357. * @param resource $parser
  1358. * @param string $data
  1359. */
  1360. function _data_handler($parser, $data)
  1361. {
  1362. if (!isset($this->current) || is_object($this->current)) {
  1363. return;
  1364. }
  1365. $this->current.= trim($data);
  1366. }
  1367. /**
  1368. * Loads a public or private key
  1369. *
  1370. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  1371. *
  1372. * @access public
  1373. * @param string $key
  1374. * @param int $type optional
  1375. */
  1376. function loadKey($key, $type = false)
  1377. {
  1378. if ($key instanceof RSA) {
  1379. $this->privateKeyFormat = $key->privateKeyFormat;
  1380. $this->publicKeyFormat = $key->publicKeyFormat;
  1381. $this->k = $key->k;
  1382. $this->hLen = $key->hLen;
  1383. $this->sLen = $key->sLen;
  1384. $this->mgfHLen = $key->mgfHLen;
  1385. $this->encryptionMode = $key->encryptionMode;
  1386. $this->signatureMode = $key->signatureMode;
  1387. $this->password = $key->password;
  1388. $this->configFile = $key->configFile;
  1389. $this->comment = $key->comment;
  1390. if (is_object($key->hash)) {
  1391. $this->hash = new Hash($key->hash->getHash());
  1392. }
  1393. if (is_object($key->mgfHash)) {
  1394. $this->mgfHash = new Hash($key->mgfHash->getHash());
  1395. }
  1396. if (is_object($key->modulus)) {
  1397. $this->modulus = $key->modulus->copy();
  1398. }
  1399. if (is_object($key->exponent)) {
  1400. $this->exponent = $key->exponent->copy();
  1401. }
  1402. if (is_object($key->publicExponent)) {
  1403. $this->publicExponent = $key->publicExponent->copy();
  1404. }
  1405. $this->primes = array();
  1406. $this->exponents = array();
  1407. $this->coefficients = array();
  1408. foreach ($this->primes as $prime) {
  1409. $this->primes[] = $prime->copy();
  1410. }
  1411. foreach ($this->exponents as $exponent) {
  1412. $this->exponents[] = $exponent->copy();
  1413. }
  1414. foreach ($this->coefficients as $coefficient) {
  1415. $this->coefficients[] = $coefficient->copy();
  1416. }
  1417. return true;
  1418. }
  1419. if ($type === false) {
  1420. $types = array(
  1421. self::PUBLIC_FORMAT_RAW,
  1422. self::PRIVATE_FORMAT_PKCS1,
  1423. self::PRIVATE_FORMAT_XML,
  1424. self::PRIVATE_FORMAT_PUTTY,
  1425. self::PUBLIC_FORMAT_OPENSSH
  1426. );
  1427. foreach ($types as $type) {
  1428. $components = $this->_parseKey($key, $type);
  1429. if ($components !== false) {
  1430. break;
  1431. }
  1432. }
  1433. } else {
  1434. $components = $this->_parseKey($key, $type);
  1435. }
  1436. if ($components === false) {
  1437. return false;
  1438. }
  1439. if (isset($components['comment']) && $components['comment'] !== false) {
  1440. $this->comment = $components['comment'];
  1441. }
  1442. $this->modulus = $components['modulus'];
  1443. $this->k = strlen($this->modulus->toBytes());
  1444. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  1445. if (isset($components['primes'])) {
  1446. $this->primes = $components['primes'];
  1447. $this->exponents = $components['exponents'];
  1448. $this->coefficients = $components['coefficients'];
  1449. $this->publicExponent = $components['publicExponent'];
  1450. } else {
  1451. $this->primes = array();
  1452. $this->exponents = array();
  1453. $this->coefficients = array();
  1454. $this->publicExponent = false;
  1455. }
  1456. switch ($type) {
  1457. case self::PUBLIC_FORMAT_OPENSSH:
  1458. case self::PUBLIC_FORMAT_RAW:
  1459. $this->setPublicKey();
  1460. break;
  1461. case self::PRIVATE_FORMAT_PKCS1:
  1462. switch (true) {
  1463. case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
  1464. case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
  1465. $this->setPublicKey();
  1466. }
  1467. }
  1468. return true;
  1469. }
  1470. /**
  1471. * Sets the password
  1472. *
  1473. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  1474. * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  1475. *
  1476. * @see self::createKey()
  1477. * @see self::loadKey()
  1478. * @access public
  1479. * @param string $password
  1480. */
  1481. function setPassword($password = false)
  1482. {
  1483. $this->password = $password;
  1484. }
  1485. /**
  1486. * Defines the public key
  1487. *
  1488. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  1489. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  1490. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  1491. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  1492. * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used
  1493. * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being
  1494. * public.
  1495. *
  1496. * Do note that when a new key is loaded the index will be cleared.
  1497. *
  1498. * Returns true on success, false on failure
  1499. *
  1500. * @see self::getPublicKey()
  1501. * @access public
  1502. * @param string $key optional
  1503. * @param int $type optional
  1504. * @return bool
  1505. */
  1506. function setPublicKey($key = false, $type = false)
  1507. {
  1508. // if a public key has already been loaded return false
  1509. if (!empty($this->publicExponent)) {
  1510. return false;
  1511. }
  1512. if ($key === false && !empty($this->modulus)) {
  1513. $this->publicExponent = $this->exponent;
  1514. return true;
  1515. }
  1516. if ($type === false) {
  1517. $types = array(
  1518. self::PUBLIC_FORMAT_RAW,
  1519. self::PUBLIC_FORMAT_PKCS1,
  1520. self::PUBLIC_FORMAT_XML,
  1521. self::PUBLIC_FORMAT_OPENSSH
  1522. );
  1523. foreach ($types as $type) {
  1524. $components = $this->_parseKey($key, $type);
  1525. if ($components !== false) {
  1526. break;
  1527. }
  1528. }
  1529. } else {
  1530. $components = $this->_parseKey($key, $type);
  1531. }
  1532. if ($components === false) {
  1533. return false;
  1534. }
  1535. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  1536. $this->modulus = $components['modulus'];
  1537. $this->exponent = $this->publicExponent = $components['publicExponent'];
  1538. return true;
  1539. }
  1540. $this->publicExponent = $components['publicExponent'];
  1541. return true;
  1542. }
  1543. /**
  1544. * Defines the private key
  1545. *
  1546. * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force
  1547. * phpseclib to treat the key as a private key. This function will do that.
  1548. *
  1549. * Do note that when a new key is loaded the index will be cleared.
  1550. *
  1551. * Returns true on success, false on failure
  1552. *
  1553. * @see self::getPublicKey()
  1554. * @access public
  1555. * @param string $key optional
  1556. * @param int $type optional
  1557. * @return bool
  1558. */
  1559. function setPrivateKey($key = false, $type = false)
  1560. {
  1561. if ($key === false && !empty($this->publicExponent)) {
  1562. $this->publicExponent = false;
  1563. return true;
  1564. }
  1565. $rsa = new RSA();
  1566. if (!$rsa->loadKey($key, $type)) {
  1567. return false;
  1568. }
  1569. $rsa->publicExponent = false;
  1570. // don't overwrite the old key if the new key is invalid
  1571. $this->loadKey($rsa);
  1572. return true;
  1573. }
  1574. /**
  1575. * Returns the public key
  1576. *
  1577. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  1578. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  1579. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  1580. *
  1581. * @see self::getPublicKey()
  1582. * @access public
  1583. * @param string $key
  1584. * @param int $type optional
  1585. */
  1586. function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8)
  1587. {
  1588. if (empty($this->modulus) || empty($this->publicExponent)) {
  1589. return false;
  1590. }
  1591. $oldFormat = $this->publicKeyFormat;
  1592. $this->publicKeyFormat = $type;
  1593. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  1594. $this->publicKeyFormat = $oldFormat;
  1595. return $temp;
  1596. }
  1597. /**
  1598. * Returns the public key's fingerprint
  1599. *
  1600. * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
  1601. * no public key currently loaded, false is returned.
  1602. * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
  1603. *
  1604. * @access public
  1605. * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
  1606. * for invalid values.
  1607. * @return mixed
  1608. */
  1609. function getPublicKeyFingerprint($algorithm = 'md5')
  1610. {
  1611. if (empty($this->modulus) || empty($this->publicExponent)) {
  1612. return false;
  1613. }
  1614. $modulus = $this->modulus->toBytes(true);
  1615. $publicExponent = $this->publicExponent->toBytes(true);
  1616. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  1617. switch ($algorithm) {
  1618. case 'sha256':
  1619. $hash = new Hash('sha256');
  1620. $base = base64_encode($hash->hash($RSAPublicKey));
  1621. return substr($base, 0, strlen($base) - 1);
  1622. case 'md5':
  1623. return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1);
  1624. default:
  1625. return false;
  1626. }
  1627. }
  1628. /**
  1629. * Returns the private key
  1630. *
  1631. * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  1632. *
  1633. * @see self::getPublicKey()
  1634. * @access public
  1635. * @param string $key
  1636. * @param int $type optional
  1637. * @return mixed
  1638. */
  1639. function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1)
  1640. {
  1641. if (empty($this->primes)) {
  1642. return false;
  1643. }
  1644. $oldFormat = $this->privateKeyFormat;
  1645. $this->privateKeyFormat = $type;
  1646. $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
  1647. $this->privateKeyFormat = $oldFormat;
  1648. return $temp;
  1649. }
  1650. /**
  1651. * Returns a minimalistic private key
  1652. *
  1653. * Returns the private key without the prime number constituants. Structurally identical to a public key that
  1654. * hasn't been set as the public key
  1655. *
  1656. * @see self::getPrivateKey()
  1657. * @access private
  1658. * @param string $key
  1659. * @param int $type optional
  1660. */
  1661. function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8)
  1662. {
  1663. if (empty($this->modulus) || empty($this->exponent)) {
  1664. return false;
  1665. }
  1666. $oldFormat = $this->publicKeyFormat;
  1667. $this->publicKeyFormat = $mode;
  1668. $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
  1669. $this->publicKeyFormat = $oldFormat;
  1670. return $temp;
  1671. }
  1672. /**
  1673. * __toString() magic method
  1674. *
  1675. * @access public
  1676. * @return string
  1677. */
  1678. function __toString()
  1679. {
  1680. $key = $this->getPrivateKey($this->privateKeyFormat);
  1681. if ($key !== false) {
  1682. return $key;
  1683. }
  1684. $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
  1685. return $key !== false ? $key : '';
  1686. }
  1687. /**
  1688. * __clone() magic method
  1689. *
  1690. * @access public
  1691. * @return Crypt_RSA
  1692. */
  1693. function __clone()
  1694. {
  1695. $key = new RSA();
  1696. $key->loadKey($this);
  1697. return $key;
  1698. }
  1699. /**
  1700. * Generates the smallest and largest numbers requiring $bits bits
  1701. *
  1702. * @access private
  1703. * @param int $bits
  1704. * @return array
  1705. */
  1706. function _generateMinMax($bits)
  1707. {
  1708. $bytes = $bits >> 3;
  1709. $min = str_repeat(chr(0), $bytes);
  1710. $max = str_repeat(chr(0xFF), $bytes);
  1711. $msb = $bits & 7;
  1712. if ($msb) {
  1713. $min = chr(1 << ($msb - 1)) . $min;
  1714. $max = chr((1 << $msb) - 1) . $max;
  1715. } else {
  1716. $min[0] = chr(0x80);
  1717. }
  1718. return array(
  1719. 'min' => new BigInteger($min, 256),
  1720. 'max' => new BigInteger($max, 256)
  1721. );
  1722. }
  1723. /**
  1724. * DER-decode the length
  1725. *
  1726. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1727. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1728. *
  1729. * @access private
  1730. * @param string $string
  1731. * @return int
  1732. */
  1733. function _decodeLength(&$string)
  1734. {
  1735. $length = ord($this->_string_shift($string));
  1736. if ($length & 0x80) { // definite length, long form
  1737. $length&= 0x7F;
  1738. $temp = $this->_string_shift($string, $length);
  1739. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1740. }
  1741. return $length;
  1742. }
  1743. /**
  1744. * DER-encode the length
  1745. *
  1746. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1747. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1748. *
  1749. * @access private
  1750. * @param int $length
  1751. * @return string
  1752. */
  1753. function _encodeLength($length)
  1754. {
  1755. if ($length <= 0x7F) {
  1756. return chr($length);
  1757. }
  1758. $temp = ltrim(pack('N', $length), chr(0));
  1759. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1760. }
  1761. /**
  1762. * String Shift
  1763. *
  1764. * Inspired by array_shift
  1765. *
  1766. * @param string $string
  1767. * @param int $index
  1768. * @return string
  1769. * @access private
  1770. */
  1771. function _string_shift(&$string, $index = 1)
  1772. {
  1773. $substr = substr($string, 0, $index);
  1774. $string = substr($string, $index);
  1775. return $substr;
  1776. }
  1777. /**
  1778. * Determines the private key format
  1779. *
  1780. * @see self::createKey()
  1781. * @access public
  1782. * @param int $format
  1783. */
  1784. function setPrivateKeyFormat($format)
  1785. {
  1786. $this->privateKeyFormat = $format;
  1787. }
  1788. /**
  1789. * Determines the public key format
  1790. *
  1791. * @see self::createKey()
  1792. * @access public
  1793. * @param int $format
  1794. */
  1795. function setPublicKeyFormat($format)
  1796. {
  1797. $this->publicKeyFormat = $format;
  1798. }
  1799. /**
  1800. * Determines which hashing function should be used
  1801. *
  1802. * Used with signature production / verification and (if the encryption mode is self::ENCRYPTION_OAEP) encryption and
  1803. * decryption. If $hash isn't supported, sha1 is used.
  1804. *
  1805. * @access public
  1806. * @param string $hash
  1807. */
  1808. function setHash($hash)
  1809. {
  1810. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1811. switch ($hash) {
  1812. case 'md2':
  1813. case 'md5':
  1814. case 'sha1':
  1815. case 'sha256':
  1816. case 'sha384':
  1817. case 'sha512':
  1818. $this->hash = new Hash($hash);
  1819. $this->hashName = $hash;
  1820. break;
  1821. default:
  1822. $this->hash = new Hash('sha1');
  1823. $this->hashName = 'sha1';
  1824. }
  1825. $this->hLen = $this->hash->getLength();
  1826. }
  1827. /**
  1828. * Determines which hashing function should be used for the mask generation function
  1829. *
  1830. * The mask generation function is used by self::ENCRYPTION_OAEP and self::SIGNATURE_PSS and although it's
  1831. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1832. *
  1833. * @access public
  1834. * @param string $hash
  1835. */
  1836. function setMGFHash($hash)
  1837. {
  1838. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1839. switch ($hash) {
  1840. case 'md2':
  1841. case 'md5':
  1842. case 'sha1':
  1843. case 'sha256':
  1844. case 'sha384':
  1845. case 'sha512':
  1846. $this->mgfHash = new Hash($hash);
  1847. break;
  1848. default:
  1849. $this->mgfHash = new Hash('sha1');
  1850. }
  1851. $this->mgfHLen = $this->mgfHash->getLength();
  1852. }
  1853. /**
  1854. * Determines the salt length
  1855. *
  1856. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1857. *
  1858. * Typical salt lengths in octets are hLen (the length of the output
  1859. * of the hash function Hash) and 0.
  1860. *
  1861. * @access public
  1862. * @param int $format
  1863. */
  1864. function setSaltLength($sLen)
  1865. {
  1866. $this->sLen = $sLen;
  1867. }
  1868. /**
  1869. * Integer-to-Octet-String primitive
  1870. *
  1871. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1872. *
  1873. * @access private
  1874. * @param \phpseclib\Math\BigInteger $x
  1875. * @param int $xLen
  1876. * @return string
  1877. */
  1878. function _i2osp($x, $xLen)
  1879. {
  1880. $x = $x->toBytes();
  1881. if (strlen($x) > $xLen) {
  1882. user_error('Integer too large');
  1883. return false;
  1884. }
  1885. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1886. }
  1887. /**
  1888. * Octet-String-to-Integer primitive
  1889. *
  1890. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1891. *
  1892. * @access private
  1893. * @param string $x
  1894. * @return \phpseclib\Math\BigInteger
  1895. */
  1896. function _os2ip($x)
  1897. {
  1898. return new BigInteger($x, 256);
  1899. }
  1900. /**
  1901. * Exponentiate with or without Chinese Remainder Theorem
  1902. *
  1903. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1904. *
  1905. * @access private
  1906. * @param \phpseclib\Math\BigInteger $x
  1907. * @return \phpseclib\Math\BigInteger
  1908. */
  1909. function _exponentiate($x)
  1910. {
  1911. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1912. return $x->modPow($this->exponent, $this->modulus);
  1913. }
  1914. $num_primes = count($this->primes);
  1915. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1916. $m_i = array(
  1917. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1918. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1919. );
  1920. $h = $m_i[1]->subtract($m_i[2]);
  1921. $h = $h->multiply($this->coefficients[2]);
  1922. list(, $h) = $h->divide($this->primes[1]);
  1923. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1924. $r = $this->primes[1];
  1925. for ($i = 3; $i <= $num_primes; $i++) {
  1926. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1927. $r = $r->multiply($this->primes[$i - 1]);
  1928. $h = $m_i->subtract($m);
  1929. $h = $h->multiply($this->coefficients[$i]);
  1930. list(, $h) = $h->divide($this->primes[$i]);
  1931. $m = $m->add($r->multiply($h));
  1932. }
  1933. } else {
  1934. $smallest = $this->primes[1];
  1935. for ($i = 2; $i <= $num_primes; $i++) {
  1936. if ($smallest->compare($this->primes[$i]) > 0) {
  1937. $smallest = $this->primes[$i];
  1938. }
  1939. }
  1940. $one = new BigInteger(1);
  1941. $r = $one->random($one, $smallest->subtract($one));
  1942. $m_i = array(
  1943. 1 => $this->_blind($x, $r, 1),
  1944. 2 => $this->_blind($x, $r, 2)
  1945. );
  1946. $h = $m_i[1]->subtract($m_i[2]);
  1947. $h = $h->multiply($this->coefficients[2]);
  1948. list(, $h) = $h->divide($this->primes[1]);
  1949. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1950. $r = $this->primes[1];
  1951. for ($i = 3; $i <= $num_primes; $i++) {
  1952. $m_i = $this->_blind($x, $r, $i);
  1953. $r = $r->multiply($this->primes[$i - 1]);
  1954. $h = $m_i->subtract($m);
  1955. $h = $h->multiply($this->coefficients[$i]);
  1956. list(, $h) = $h->divide($this->primes[$i]);
  1957. $m = $m->add($r->multiply($h));
  1958. }
  1959. }
  1960. return $m;
  1961. }
  1962. /**
  1963. * Performs RSA Blinding
  1964. *
  1965. * Protects against timing attacks by employing RSA Blinding.
  1966. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1967. *
  1968. * @access private
  1969. * @param \phpseclib\Math\BigInteger $x
  1970. * @param \phpseclib\Math\BigInteger $r
  1971. * @param int $i
  1972. * @return \phpseclib\Math\BigInteger
  1973. */
  1974. function _blind($x, $r, $i)
  1975. {
  1976. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1977. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1978. $r = $r->modInverse($this->primes[$i]);
  1979. $x = $x->multiply($r);
  1980. list(, $x) = $x->divide($this->primes[$i]);
  1981. return $x;
  1982. }
  1983. /**
  1984. * Performs blinded RSA equality testing
  1985. *
  1986. * Protects against a particular type of timing attack described.
  1987. *
  1988. * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
  1989. *
  1990. * Thanks for the heads up singpolyma!
  1991. *
  1992. * @access private
  1993. * @param string $x
  1994. * @param string $y
  1995. * @return bool
  1996. */
  1997. function _equals($x, $y)
  1998. {
  1999. if (strlen($x) != strlen($y)) {
  2000. return false;
  2001. }
  2002. $result = 0;
  2003. for ($i = 0; $i < strlen($x); $i++) {
  2004. $result |= ord($x[$i]) ^ ord($y[$i]);
  2005. }
  2006. return $result == 0;
  2007. }
  2008. /**
  2009. * RSAEP
  2010. *
  2011. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  2012. *
  2013. * @access private
  2014. * @param \phpseclib\Math\BigInteger $m
  2015. * @return \phpseclib\Math\BigInteger
  2016. */
  2017. function _rsaep($m)
  2018. {
  2019. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  2020. user_error('Message representative out of range');
  2021. return false;
  2022. }
  2023. return $this->_exponentiate($m);
  2024. }
  2025. /**
  2026. * RSADP
  2027. *
  2028. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  2029. *
  2030. * @access private
  2031. * @param \phpseclib\Math\BigInteger $c
  2032. * @return \phpseclib\Math\BigInteger
  2033. */
  2034. function _rsadp($c)
  2035. {
  2036. if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
  2037. user_error('Ciphertext representative out of range');
  2038. return false;
  2039. }
  2040. return $this->_exponentiate($c);
  2041. }
  2042. /**
  2043. * RSASP1
  2044. *
  2045. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  2046. *
  2047. * @access private
  2048. * @param \phpseclib\Math\BigInteger $m
  2049. * @return \phpseclib\Math\BigInteger
  2050. */
  2051. function _rsasp1($m)
  2052. {
  2053. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  2054. user_error('Message representative out of range');
  2055. return false;
  2056. }
  2057. return $this->_exponentiate($m);
  2058. }
  2059. /**
  2060. * RSAVP1
  2061. *
  2062. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  2063. *
  2064. * @access private
  2065. * @param \phpseclib\Math\BigInteger $s
  2066. * @return \phpseclib\Math\BigInteger
  2067. */
  2068. function _rsavp1($s)
  2069. {
  2070. if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
  2071. user_error('Signature representative out of range');
  2072. return false;
  2073. }
  2074. return $this->_exponentiate($s);
  2075. }
  2076. /**
  2077. * MGF1
  2078. *
  2079. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  2080. *
  2081. * @access private
  2082. * @param string $mgfSeed
  2083. * @param int $mgfLen
  2084. * @return string
  2085. */
  2086. function _mgf1($mgfSeed, $maskLen)
  2087. {
  2088. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  2089. $t = '';
  2090. $count = ceil($maskLen / $this->mgfHLen);
  2091. for ($i = 0; $i < $count; $i++) {
  2092. $c = pack('N', $i);
  2093. $t.= $this->mgfHash->hash($mgfSeed . $c);
  2094. }
  2095. return substr($t, 0, $maskLen);
  2096. }
  2097. /**
  2098. * RSAES-OAEP-ENCRYPT
  2099. *
  2100. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  2101. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  2102. *
  2103. * @access private
  2104. * @param string $m
  2105. * @param string $l
  2106. * @return string
  2107. */
  2108. function _rsaes_oaep_encrypt($m, $l = '')
  2109. {
  2110. $mLen = strlen($m);
  2111. // Length checking
  2112. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2113. // be output.
  2114. if ($mLen > $this->k - 2 * $this->hLen - 2) {
  2115. user_error('Message too long');
  2116. return false;
  2117. }
  2118. // EME-OAEP encoding
  2119. $lHash = $this->hash->hash($l);
  2120. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  2121. $db = $lHash . $ps . chr(1) . $m;
  2122. $seed = Random::string($this->hLen);
  2123. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2124. $maskedDB = $db ^ $dbMask;
  2125. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2126. $maskedSeed = $seed ^ $seedMask;
  2127. $em = chr(0) . $maskedSeed . $maskedDB;
  2128. // RSA encryption
  2129. $m = $this->_os2ip($em);
  2130. $c = $this->_rsaep($m);
  2131. $c = $this->_i2osp($c, $this->k);
  2132. // Output the ciphertext C
  2133. return $c;
  2134. }
  2135. /**
  2136. * RSAES-OAEP-DECRYPT
  2137. *
  2138. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  2139. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  2140. *
  2141. * Note. Care must be taken to ensure that an opponent cannot
  2142. * distinguish the different error conditions in Step 3.g, whether by
  2143. * error message or timing, or, more generally, learn partial
  2144. * information about the encoded message EM. Otherwise an opponent may
  2145. * be able to obtain useful information about the decryption of the
  2146. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  2147. * observed by Manger [36].
  2148. *
  2149. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  2150. *
  2151. * Both the encryption and the decryption operations of RSAES-OAEP take
  2152. * the value of a label L as input. In this version of PKCS #1, L is
  2153. * the empty string; other uses of the label are outside the scope of
  2154. * this document.
  2155. *
  2156. * @access private
  2157. * @param string $c
  2158. * @param string $l
  2159. * @return string
  2160. */
  2161. function _rsaes_oaep_decrypt($c, $l = '')
  2162. {
  2163. // Length checking
  2164. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2165. // be output.
  2166. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  2167. user_error('Decryption error');
  2168. return false;
  2169. }
  2170. // RSA decryption
  2171. $c = $this->_os2ip($c);
  2172. $m = $this->_rsadp($c);
  2173. if ($m === false) {
  2174. user_error('Decryption error');
  2175. return false;
  2176. }
  2177. $em = $this->_i2osp($m, $this->k);
  2178. // EME-OAEP decoding
  2179. $lHash = $this->hash->hash($l);
  2180. $y = ord($em[0]);
  2181. $maskedSeed = substr($em, 1, $this->hLen);
  2182. $maskedDB = substr($em, $this->hLen + 1);
  2183. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  2184. $seed = $maskedSeed ^ $seedMask;
  2185. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  2186. $db = $maskedDB ^ $dbMask;
  2187. $lHash2 = substr($db, 0, $this->hLen);
  2188. $m = substr($db, $this->hLen);
  2189. if ($lHash != $lHash2) {
  2190. user_error('Decryption error');
  2191. return false;
  2192. }
  2193. $m = ltrim($m, chr(0));
  2194. if (ord($m[0]) != 1) {
  2195. user_error('Decryption error');
  2196. return false;
  2197. }
  2198. // Output the message M
  2199. return substr($m, 1);
  2200. }
  2201. /**
  2202. * Raw Encryption / Decryption
  2203. *
  2204. * Doesn't use padding and is not recommended.
  2205. *
  2206. * @access private
  2207. * @param string $m
  2208. * @return string
  2209. */
  2210. function _raw_encrypt($m)
  2211. {
  2212. $temp = $this->_os2ip($m);
  2213. $temp = $this->_rsaep($temp);
  2214. return $this->_i2osp($temp, $this->k);
  2215. }
  2216. /**
  2217. * RSAES-PKCS1-V1_5-ENCRYPT
  2218. *
  2219. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  2220. *
  2221. * @access private
  2222. * @param string $m
  2223. * @return string
  2224. */
  2225. function _rsaes_pkcs1_v1_5_encrypt($m)
  2226. {
  2227. $mLen = strlen($m);
  2228. // Length checking
  2229. if ($mLen > $this->k - 11) {
  2230. user_error('Message too long');
  2231. return false;
  2232. }
  2233. // EME-PKCS1-v1_5 encoding
  2234. $psLen = $this->k - $mLen - 3;
  2235. $ps = '';
  2236. while (strlen($ps) != $psLen) {
  2237. $temp = Random::string($psLen - strlen($ps));
  2238. $temp = str_replace("\x00", '', $temp);
  2239. $ps.= $temp;
  2240. }
  2241. $type = 2;
  2242. // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  2243. if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
  2244. $type = 1;
  2245. // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  2246. $ps = str_repeat("\xFF", $psLen);
  2247. }
  2248. $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  2249. // RSA encryption
  2250. $m = $this->_os2ip($em);
  2251. $c = $this->_rsaep($m);
  2252. $c = $this->_i2osp($c, $this->k);
  2253. // Output the ciphertext C
  2254. return $c;
  2255. }
  2256. /**
  2257. * RSAES-PKCS1-V1_5-DECRYPT
  2258. *
  2259. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  2260. *
  2261. * For compatibility purposes, this function departs slightly from the description given in RFC3447.
  2262. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  2263. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  2264. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  2265. * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
  2266. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  2267. *
  2268. * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt
  2269. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  2270. * not private key encrypted ciphertext's.
  2271. *
  2272. * @access private
  2273. * @param string $c
  2274. * @return string
  2275. */
  2276. function _rsaes_pkcs1_v1_5_decrypt($c)
  2277. {
  2278. // Length checking
  2279. if (strlen($c) != $this->k) { // or if k < 11
  2280. user_error('Decryption error');
  2281. return false;
  2282. }
  2283. // RSA decryption
  2284. $c = $this->_os2ip($c);
  2285. $m = $this->_rsadp($c);
  2286. if ($m === false) {
  2287. user_error('Decryption error');
  2288. return false;
  2289. }
  2290. $em = $this->_i2osp($m, $this->k);
  2291. // EME-PKCS1-v1_5 decoding
  2292. if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  2293. user_error('Decryption error');
  2294. return false;
  2295. }
  2296. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  2297. $m = substr($em, strlen($ps) + 3);
  2298. if (strlen($ps) < 8) {
  2299. user_error('Decryption error');
  2300. return false;
  2301. }
  2302. // Output M
  2303. return $m;
  2304. }
  2305. /**
  2306. * EMSA-PSS-ENCODE
  2307. *
  2308. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  2309. *
  2310. * @access private
  2311. * @param string $m
  2312. * @param int $emBits
  2313. */
  2314. function _emsa_pss_encode($m, $emBits)
  2315. {
  2316. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2317. // be output.
  2318. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  2319. $sLen = $this->sLen ? $this->sLen : $this->hLen;
  2320. $mHash = $this->hash->hash($m);
  2321. if ($emLen < $this->hLen + $sLen + 2) {
  2322. user_error('Encoding error');
  2323. return false;
  2324. }
  2325. $salt = Random::string($sLen);
  2326. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2327. $h = $this->hash->hash($m2);
  2328. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  2329. $db = $ps . chr(1) . $salt;
  2330. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2331. $maskedDB = $db ^ $dbMask;
  2332. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  2333. $em = $maskedDB . $h . chr(0xBC);
  2334. return $em;
  2335. }
  2336. /**
  2337. * EMSA-PSS-VERIFY
  2338. *
  2339. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  2340. *
  2341. * @access private
  2342. * @param string $m
  2343. * @param string $em
  2344. * @param int $emBits
  2345. * @return string
  2346. */
  2347. function _emsa_pss_verify($m, $em, $emBits)
  2348. {
  2349. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2350. // be output.
  2351. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  2352. $sLen = $this->sLen ? $this->sLen : $this->hLen;
  2353. $mHash = $this->hash->hash($m);
  2354. if ($emLen < $this->hLen + $sLen + 2) {
  2355. return false;
  2356. }
  2357. if ($em[strlen($em) - 1] != chr(0xBC)) {
  2358. return false;
  2359. }
  2360. $maskedDB = substr($em, 0, -$this->hLen - 1);
  2361. $h = substr($em, -$this->hLen - 1, $this->hLen);
  2362. $temp = chr(0xFF << ($emBits & 7));
  2363. if ((~$maskedDB[0] & $temp) != $temp) {
  2364. return false;
  2365. }
  2366. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2367. $db = $maskedDB ^ $dbMask;
  2368. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  2369. $temp = $emLen - $this->hLen - $sLen - 2;
  2370. if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  2371. return false;
  2372. }
  2373. $salt = substr($db, $temp + 1); // should be $sLen long
  2374. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2375. $h2 = $this->hash->hash($m2);
  2376. return $this->_equals($h, $h2);
  2377. }
  2378. /**
  2379. * RSASSA-PSS-SIGN
  2380. *
  2381. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  2382. *
  2383. * @access private
  2384. * @param string $m
  2385. * @return string
  2386. */
  2387. function _rsassa_pss_sign($m)
  2388. {
  2389. // EMSA-PSS encoding
  2390. $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  2391. // RSA signature
  2392. $m = $this->_os2ip($em);
  2393. $s = $this->_rsasp1($m);
  2394. $s = $this->_i2osp($s, $this->k);
  2395. // Output the signature S
  2396. return $s;
  2397. }
  2398. /**
  2399. * RSASSA-PSS-VERIFY
  2400. *
  2401. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  2402. *
  2403. * @access private
  2404. * @param string $m
  2405. * @param string $s
  2406. * @return string
  2407. */
  2408. function _rsassa_pss_verify($m, $s)
  2409. {
  2410. // Length checking
  2411. if (strlen($s) != $this->k) {
  2412. user_error('Invalid signature');
  2413. return false;
  2414. }
  2415. // RSA verification
  2416. $modBits = 8 * $this->k;
  2417. $s2 = $this->_os2ip($s);
  2418. $m2 = $this->_rsavp1($s2);
  2419. if ($m2 === false) {
  2420. user_error('Invalid signature');
  2421. return false;
  2422. }
  2423. $em = $this->_i2osp($m2, $modBits >> 3);
  2424. if ($em === false) {
  2425. user_error('Invalid signature');
  2426. return false;
  2427. }
  2428. // EMSA-PSS verification
  2429. return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  2430. }
  2431. /**
  2432. * EMSA-PKCS1-V1_5-ENCODE
  2433. *
  2434. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  2435. *
  2436. * @access private
  2437. * @param string $m
  2438. * @param int $emLen
  2439. * @return string
  2440. */
  2441. function _emsa_pkcs1_v1_5_encode($m, $emLen)
  2442. {
  2443. $h = $this->hash->hash($m);
  2444. if ($h === false) {
  2445. return false;
  2446. }
  2447. // see http://tools.ietf.org/html/rfc3447#page-43
  2448. switch ($this->hashName) {
  2449. case 'md2':
  2450. $t = pack('H*', '3020300c06082a864886f70d020205000410');
  2451. break;
  2452. case 'md5':
  2453. $t = pack('H*', '3020300c06082a864886f70d020505000410');
  2454. break;
  2455. case 'sha1':
  2456. $t = pack('H*', '3021300906052b0e03021a05000414');
  2457. break;
  2458. case 'sha256':
  2459. $t = pack('H*', '3031300d060960864801650304020105000420');
  2460. break;
  2461. case 'sha384':
  2462. $t = pack('H*', '3041300d060960864801650304020205000430');
  2463. break;
  2464. case 'sha512':
  2465. $t = pack('H*', '3051300d060960864801650304020305000440');
  2466. }
  2467. $t.= $h;
  2468. $tLen = strlen($t);
  2469. if ($emLen < $tLen + 11) {
  2470. user_error('Intended encoded message length too short');
  2471. return false;
  2472. }
  2473. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  2474. $em = "\0\1$ps\0$t";
  2475. return $em;
  2476. }
  2477. /**
  2478. * RSASSA-PKCS1-V1_5-SIGN
  2479. *
  2480. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  2481. *
  2482. * @access private
  2483. * @param string $m
  2484. * @return string
  2485. */
  2486. function _rsassa_pkcs1_v1_5_sign($m)
  2487. {
  2488. // EMSA-PKCS1-v1_5 encoding
  2489. $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2490. if ($em === false) {
  2491. user_error('RSA modulus too short');
  2492. return false;
  2493. }
  2494. // RSA signature
  2495. $m = $this->_os2ip($em);
  2496. $s = $this->_rsasp1($m);
  2497. $s = $this->_i2osp($s, $this->k);
  2498. // Output the signature S
  2499. return $s;
  2500. }
  2501. /**
  2502. * RSASSA-PKCS1-V1_5-VERIFY
  2503. *
  2504. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  2505. *
  2506. * @access private
  2507. * @param string $m
  2508. * @return string
  2509. */
  2510. function _rsassa_pkcs1_v1_5_verify($m, $s)
  2511. {
  2512. // Length checking
  2513. if (strlen($s) != $this->k) {
  2514. user_error('Invalid signature');
  2515. return false;
  2516. }
  2517. // RSA verification
  2518. $s = $this->_os2ip($s);
  2519. $m2 = $this->_rsavp1($s);
  2520. if ($m2 === false) {
  2521. user_error('Invalid signature');
  2522. return false;
  2523. }
  2524. $em = $this->_i2osp($m2, $this->k);
  2525. if ($em === false) {
  2526. user_error('Invalid signature');
  2527. return false;
  2528. }
  2529. // EMSA-PKCS1-v1_5 encoding
  2530. $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2531. if ($em2 === false) {
  2532. user_error('RSA modulus too short');
  2533. return false;
  2534. }
  2535. // Compare
  2536. return $this->_equals($em, $em2);
  2537. }
  2538. /**
  2539. * Set Encryption Mode
  2540. *
  2541. * Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1.
  2542. *
  2543. * @access public
  2544. * @param int $mode
  2545. */
  2546. function setEncryptionMode($mode)
  2547. {
  2548. $this->encryptionMode = $mode;
  2549. }
  2550. /**
  2551. * Set Signature Mode
  2552. *
  2553. * Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1
  2554. *
  2555. * @access public
  2556. * @param int $mode
  2557. */
  2558. function setSignatureMode($mode)
  2559. {
  2560. $this->signatureMode = $mode;
  2561. }
  2562. /**
  2563. * Set public key comment.
  2564. *
  2565. * @access public
  2566. * @param string $comment
  2567. */
  2568. function setComment($comment)
  2569. {
  2570. $this->comment = $comment;
  2571. }
  2572. /**
  2573. * Get public key comment.
  2574. *
  2575. * @access public
  2576. * @return string
  2577. */
  2578. function getComment()
  2579. {
  2580. return $this->comment;
  2581. }
  2582. /**
  2583. * Encryption
  2584. *
  2585. * Both self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
  2586. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  2587. * be concatenated together.
  2588. *
  2589. * @see self::decrypt()
  2590. * @access public
  2591. * @param string $plaintext
  2592. * @return string
  2593. */
  2594. function encrypt($plaintext)
  2595. {
  2596. switch ($this->encryptionMode) {
  2597. case self::ENCRYPTION_NONE:
  2598. $plaintext = str_split($plaintext, $this->k);
  2599. $ciphertext = '';
  2600. foreach ($plaintext as $m) {
  2601. $ciphertext.= $this->_raw_encrypt($m);
  2602. }
  2603. return $ciphertext;
  2604. case self::ENCRYPTION_PKCS1:
  2605. $length = $this->k - 11;
  2606. if ($length <= 0) {
  2607. return false;
  2608. }
  2609. $plaintext = str_split($plaintext, $length);
  2610. $ciphertext = '';
  2611. foreach ($plaintext as $m) {
  2612. $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
  2613. }
  2614. return $ciphertext;
  2615. //case self::ENCRYPTION_OAEP:
  2616. default:
  2617. $length = $this->k - 2 * $this->hLen - 2;
  2618. if ($length <= 0) {
  2619. return false;
  2620. }
  2621. $plaintext = str_split($plaintext, $length);
  2622. $ciphertext = '';
  2623. foreach ($plaintext as $m) {
  2624. $ciphertext.= $this->_rsaes_oaep_encrypt($m);
  2625. }
  2626. return $ciphertext;
  2627. }
  2628. }
  2629. /**
  2630. * Decryption
  2631. *
  2632. * @see self::encrypt()
  2633. * @access public
  2634. * @param string $plaintext
  2635. * @return string
  2636. */
  2637. function decrypt($ciphertext)
  2638. {
  2639. if ($this->k <= 0) {
  2640. return false;
  2641. }
  2642. $ciphertext = str_split($ciphertext, $this->k);
  2643. $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
  2644. $plaintext = '';
  2645. switch ($this->encryptionMode) {
  2646. case self::ENCRYPTION_NONE:
  2647. $decrypt = '_raw_encrypt';
  2648. break;
  2649. case self::ENCRYPTION_PKCS1:
  2650. $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
  2651. break;
  2652. //case self::ENCRYPTION_OAEP:
  2653. default:
  2654. $decrypt = '_rsaes_oaep_decrypt';
  2655. }
  2656. foreach ($ciphertext as $c) {
  2657. $temp = $this->$decrypt($c);
  2658. if ($temp === false) {
  2659. return false;
  2660. }
  2661. $plaintext.= $temp;
  2662. }
  2663. return $plaintext;
  2664. }
  2665. /**
  2666. * Create a signature
  2667. *
  2668. * @see self::verify()
  2669. * @access public
  2670. * @param string $message
  2671. * @return string
  2672. */
  2673. function sign($message)
  2674. {
  2675. if (empty($this->modulus) || empty($this->exponent)) {
  2676. return false;
  2677. }
  2678. switch ($this->signatureMode) {
  2679. case self::SIGNATURE_PKCS1:
  2680. return $this->_rsassa_pkcs1_v1_5_sign($message);
  2681. //case self::SIGNATURE_PSS:
  2682. default:
  2683. return $this->_rsassa_pss_sign($message);
  2684. }
  2685. }
  2686. /**
  2687. * Verifies a signature
  2688. *
  2689. * @see self::sign()
  2690. * @access public
  2691. * @param string $message
  2692. * @param string $signature
  2693. * @return bool
  2694. */
  2695. function verify($message, $signature)
  2696. {
  2697. if (empty($this->modulus) || empty($this->exponent)) {
  2698. return false;
  2699. }
  2700. switch ($this->signatureMode) {
  2701. case self::SIGNATURE_PKCS1:
  2702. return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  2703. //case self::SIGNATURE_PSS:
  2704. default:
  2705. return $this->_rsassa_pss_verify($message, $signature);
  2706. }
  2707. }
  2708. /**
  2709. * Extract raw BER from Base64 encoding
  2710. *
  2711. * @access private
  2712. * @param string $str
  2713. * @return string
  2714. */
  2715. function _extractBER($str)
  2716. {
  2717. /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them
  2718. * above and beyond the ceritificate.
  2719. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line:
  2720. *
  2721. * Bag Attributes
  2722. * localKeyID: 01 00 00 00
  2723. * subject=/O=organization/OU=org unit/CN=common name
  2724. * issuer=/O=organization/CN=common name
  2725. */
  2726. $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1);
  2727. // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
  2728. $temp = preg_replace('#-+[^-]+-+#', '', $temp);
  2729. // remove new lines
  2730. $temp = str_replace(array("\r", "\n", ' '), '', $temp);
  2731. $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
  2732. return $temp != false ? $temp : $str;
  2733. }
  2734. }