PageRenderTime 36ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

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

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