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

/protected/vendors/phpseclib/Crypt/RSA.php

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