PageRenderTime 55ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/phpseclib/Crypt/RSA.php

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