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

/phpseclib/Crypt/RSA.php

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