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

/system/expressionengine/third_party/updater/libraries/phpseclib/Crypt/RSA.php

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