PageRenderTime 67ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/application/library/PhpSecure/Crypt/RSA.php

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