RSA.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. <?php
  2. /**
  3. * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  4. *
  5. * PHP version 5
  6. *
  7. * Here's an example of how to encrypt and decrypt text with this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * extract(\phpseclib\Crypt\RSA::createKey());
  13. *
  14. * $plaintext = 'terrafrost';
  15. *
  16. * $ciphertext = $publickey->encrypt($plaintext);
  17. *
  18. * echo $privatekey->decrypt($ciphertext);
  19. * ?>
  20. * </code>
  21. *
  22. * Here's an example of how to create signatures and verify signatures with this library:
  23. * <code>
  24. * <?php
  25. * include 'vendor/autoload.php';
  26. *
  27. * extract(\phpseclib\Crypt\RSA::createKey());
  28. *
  29. * $plaintext = 'terrafrost';
  30. *
  31. * $signature = $privatekey->sign($plaintext);
  32. *
  33. * echo $publickey->verify($plaintext, $signature) ? 'verified' : 'unverified';
  34. * ?>
  35. * </code>
  36. *
  37. * @category Crypt
  38. * @package RSA
  39. * @author Jim Wigginton <terrafrost@php.net>
  40. * @copyright 2009 Jim Wigginton
  41. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  42. * @link http://phpseclib.sourceforge.net
  43. */
  44. namespace phpseclib\Crypt;
  45. use ParagonIE\ConstantTime\Base64;
  46. use phpseclib\File\ASN1;
  47. use phpseclib\Math\BigInteger;
  48. use phpseclib\Common\Functions\Strings;
  49. use phpseclib\File\ASN1\Maps\DigestInfo;
  50. use phpseclib\Crypt\Common\AsymmetricKey;
  51. use phpseclib\Exception\UnsupportedAlgorithmException;
  52. /**
  53. * Pure-PHP PKCS#1 compliant implementation of RSA.
  54. *
  55. * @package RSA
  56. * @author Jim Wigginton <terrafrost@php.net>
  57. * @access public
  58. */
  59. class RSA extends AsymmetricKey
  60. {
  61. /**
  62. * Algorithm Name
  63. *
  64. * @var string
  65. * @access private
  66. */
  67. const ALGORITHM = 'RSA';
  68. /**#@+
  69. * @access public
  70. * @see self::encrypt()
  71. * @see self::decrypt()
  72. */
  73. /**
  74. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  75. * (OAEP) for encryption / decryption.
  76. *
  77. * Uses sha256 by default
  78. *
  79. * @see self::setHash()
  80. * @see self::setMGFHash()
  81. */
  82. const PADDING_OAEP = 1;
  83. /**
  84. * Use PKCS#1 padding.
  85. *
  86. * Although self::PADDING_OAEP / self::PADDING_PSS offers more security, including PKCS#1 padding is necessary for purposes of backwards
  87. * compatibility with protocols (like SSH-1) written before OAEP's introduction.
  88. */
  89. const PADDING_PKCS1 = 2;
  90. /**
  91. * Do not use any padding
  92. *
  93. * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
  94. * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
  95. */
  96. const PADDING_NONE = 3;
  97. /**
  98. * Use PKCS#1 padding with PKCS1 v1.5 compatibility
  99. *
  100. * A PKCS1 v2.1 encrypted message may not successfully decrypt with a PKCS1 v1.5 implementation (such as OpenSSL).
  101. */
  102. const PADDING_PKCS15_COMPAT = 6;
  103. /**#@-*/
  104. /**#@+
  105. * @access public
  106. * @see self::sign()
  107. * @see self::verify()
  108. * @see self::setHash()
  109. */
  110. /**
  111. * Use the Probabilistic Signature Scheme for signing
  112. *
  113. * Uses sha256 and 0 as the salt length
  114. *
  115. * @see self::setSaltLength()
  116. * @see self::setMGFHash()
  117. * @see self::setHash()
  118. */
  119. const PADDING_PSS = 4;
  120. /**
  121. * Use a relaxed version of PKCS#1 padding for signature verification
  122. */
  123. const PADDING_RELAXED_PKCS1 = 5;
  124. /**#@-*/
  125. /**
  126. * Modulus (ie. n)
  127. *
  128. * @var \phpseclib\Math\BigInteger
  129. * @access private
  130. */
  131. private $modulus;
  132. /**
  133. * Modulus length
  134. *
  135. * @var \phpseclib\Math\BigInteger
  136. * @access private
  137. */
  138. private $k;
  139. /**
  140. * Exponent (ie. e or d)
  141. *
  142. * @var \phpseclib\Math\BigInteger
  143. * @access private
  144. */
  145. private $exponent;
  146. /**
  147. * Primes for Chinese Remainder Theorem (ie. p and q)
  148. *
  149. * @var array
  150. * @access private
  151. */
  152. private $primes;
  153. /**
  154. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  155. *
  156. * @var array
  157. * @access private
  158. */
  159. private $exponents;
  160. /**
  161. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  162. *
  163. * @var array
  164. * @access private
  165. */
  166. private $coefficients;
  167. /**
  168. * Hash name
  169. *
  170. * @var string
  171. * @access private
  172. */
  173. private $hashName;
  174. /**
  175. * Length of hash function output
  176. *
  177. * @var int
  178. * @access private
  179. */
  180. private $hLen;
  181. /**
  182. * Length of salt
  183. *
  184. * @var int
  185. * @access private
  186. */
  187. private $sLen;
  188. /**
  189. * Hash function for the Mask Generation Function
  190. *
  191. * @var \phpseclib\Crypt\Hash
  192. * @access private
  193. */
  194. private $mgfHash;
  195. /**
  196. * Length of MGF hash function output
  197. *
  198. * @var int
  199. * @access private
  200. */
  201. private $mgfHLen;
  202. /**
  203. * Public Exponent
  204. *
  205. * @var mixed
  206. * @access private
  207. */
  208. private $publicExponent = false;
  209. /**
  210. * Public exponent
  211. *
  212. * @var int
  213. * @link http://en.wikipedia.org/wiki/65537_%28number%29
  214. * @access private
  215. */
  216. private static $defaultExponent = 65537;
  217. /**
  218. * Smallest Prime
  219. *
  220. * Per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  221. * than 256 bits. As a consequence if the key you're trying to create is 1024 bits and you've set smallestPrime
  222. * to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). At least if
  223. * engine is set to self::ENGINE_INTERNAL. If Engine is set to self::ENGINE_OPENSSL then smallest Prime is
  224. * ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key generation when there's
  225. * a chance neither gmp nor OpenSSL are installed)
  226. *
  227. * @var int
  228. * @access private
  229. */
  230. private static $smallestPrime = 4096;
  231. /**
  232. * The constructor
  233. *
  234. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  235. * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  236. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  237. *
  238. * @return \phpseclib\Crypt\RSA
  239. * @access public
  240. */
  241. public function __construct()
  242. {
  243. parent::__construct();
  244. //$this->hash = new Hash('sha256');
  245. $this->hLen = $this->hash->getLengthInBytes();
  246. $this->hashName = 'sha256';
  247. $this->mgfHash = new Hash('sha256');
  248. $this->mgfHLen = $this->mgfHash->getLengthInBytes();
  249. }
  250. /**
  251. * Sets the public exponent
  252. *
  253. * This will be 65537 unless changed.
  254. *
  255. * @access public
  256. * @param int $val
  257. */
  258. public static function setExponent($val)
  259. {
  260. self::$defaultExponent = $val;
  261. }
  262. /**
  263. * Sets the smallest prime number in bits
  264. *
  265. * This will be 4096 unless changed.
  266. *
  267. * @access public
  268. * @param int $val
  269. */
  270. public static function setSmallestPrime($val)
  271. {
  272. self::$smallestPrime = $val;
  273. }
  274. /**
  275. * Create public / private key pair
  276. *
  277. * Returns an array with the following two elements:
  278. * - 'privatekey': The private key.
  279. * - 'publickey': The public key.
  280. *
  281. * @access public
  282. * @param int $bits
  283. * @param array $p
  284. */
  285. public static function createKey($bits = 2048)
  286. {
  287. self::initialize_static_variables();
  288. if (!isset(self::$engine)) {
  289. self::setPreferredEngine(self::ENGINE_OPENSSL);
  290. }
  291. // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  292. if (self::$engine == self::ENGINE_OPENSSL && $bits >= 384 && self::$defaultExponent == 65537) {
  293. $config = [];
  294. if (isset(self::$configFile)) {
  295. $config['config'] = self::$configFile;
  296. }
  297. $rsa = openssl_pkey_new(['private_key_bits' => $bits] + $config);
  298. openssl_pkey_export($rsa, $privatekeystr, null, $config);
  299. $privatekey = new RSA();
  300. $privatekey->load($privatekeystr);
  301. $publickeyarr = openssl_pkey_get_details($rsa);
  302. $publickey = new RSA();
  303. $publickey->load($publickeyarr['key']);
  304. $publickey->setPublicKey();
  305. // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  306. while (openssl_error_string() !== false) {
  307. }
  308. return compact('privatekey', 'publickey');
  309. }
  310. static $e;
  311. if (!isset($e)) {
  312. $e = new BigInteger(self::$defaultExponent);
  313. }
  314. $regSize = $bits >> 1; // divide by two to see how many bits P and Q would be
  315. if ($regSize > self::$smallestPrime) {
  316. $num_primes = floor($bits / self::$smallestPrime);
  317. $regSize = self::$smallestPrime;
  318. } else {
  319. $num_primes = 2;
  320. }
  321. $n = clone self::$one;
  322. $exponents = $coefficients = $primes = [];
  323. $lcm = [
  324. 'top' => clone self::$one,
  325. 'bottom' => false
  326. ];
  327. do {
  328. for ($i = 1; $i <= $num_primes; $i++) {
  329. if ($i != $num_primes) {
  330. $primes[$i] = BigInteger::randomPrime($regSize);
  331. } else {
  332. extract(BigInteger::minMaxBits($bits));
  333. list($min) = $min->divide($n);
  334. $min = $min->add(self::$one);
  335. list($max) = $max->divide($n);
  336. $primes[$i] = BigInteger::randomRangePrime($min, $max);
  337. }
  338. // the first coefficient is calculated differently from the rest
  339. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  340. if ($i > 2) {
  341. $coefficients[$i] = $n->modInverse($primes[$i]);
  342. }
  343. $n = $n->multiply($primes[$i]);
  344. $temp = $primes[$i]->subtract(self::$one);
  345. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  346. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  347. $lcm['top'] = $lcm['top']->multiply($temp);
  348. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  349. }
  350. list($temp) = $lcm['top']->divide($lcm['bottom']);
  351. $gcd = $temp->gcd($e);
  352. $i0 = 1;
  353. } while (!$gcd->equals(self::$one));
  354. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  355. $d = $e->modInverse($temp);
  356. foreach ($primes as $i => $prime) {
  357. $temp = $prime->subtract(self::$one);
  358. $exponents[$i] = $e->modInverse($temp);
  359. }
  360. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  361. // RSAPrivateKey ::= SEQUENCE {
  362. // version Version,
  363. // modulus INTEGER, -- n
  364. // publicExponent INTEGER, -- e
  365. // privateExponent INTEGER, -- d
  366. // prime1 INTEGER, -- p
  367. // prime2 INTEGER, -- q
  368. // exponent1 INTEGER, -- d mod (p-1)
  369. // exponent2 INTEGER, -- d mod (q-1)
  370. // coefficient INTEGER, -- (inverse of q) mod p
  371. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  372. // }
  373. $privatekey = new RSA();
  374. $privatekey->modulus = $n;
  375. $privatekey->k = $bits >> 3;
  376. $privatekey->publicExponent = $e;
  377. $privatekey->exponent = $d;
  378. $privatekey->privateExponent = $e;
  379. $privatekey->primes = $primes;
  380. $privatekey->exponents = $exponents;
  381. $privatekey->coefficients = $coefficients;
  382. $publickey = new RSA();
  383. $publickey->modulus = $n;
  384. $publickey->k = $bits >> 3;
  385. $publickey->exponent = $e;
  386. $publickey->publicExponent = $e;
  387. return compact('privatekey', 'publickey');
  388. }
  389. /**
  390. * Loads a public or private key
  391. *
  392. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  393. *
  394. * @access public
  395. * @param string $key
  396. * @param int $type optional
  397. */
  398. public function load($key, $type = false)
  399. {
  400. if ($key instanceof RSA) {
  401. $this->privateKeyFormat = $key->privateKeyFormat;
  402. $this->publicKeyFormat = $key->publicKeyFormat;
  403. $this->format = $key->format;
  404. $this->k = $key->k;
  405. $this->hLen = $key->hLen;
  406. $this->sLen = $key->sLen;
  407. $this->mgfHLen = $key->mgfHLen;
  408. $this->password = $key->password;
  409. if (is_object($key->hash)) {
  410. $this->hash = new Hash($key->hash->getHash());
  411. }
  412. if (is_object($key->mgfHash)) {
  413. $this->mgfHash = new Hash($key->mgfHash->getHash());
  414. }
  415. if (is_object($key->modulus)) {
  416. $this->modulus = clone $key->modulus;
  417. }
  418. if (is_object($key->exponent)) {
  419. $this->exponent = clone $key->exponent;
  420. }
  421. if (is_object($key->publicExponent)) {
  422. $this->publicExponent = clone $key->publicExponent;
  423. }
  424. $this->primes = [];
  425. $this->exponents = [];
  426. $this->coefficients = [];
  427. foreach ($this->primes as $prime) {
  428. $this->primes[] = clone $prime;
  429. }
  430. foreach ($this->exponents as $exponent) {
  431. $this->exponents[] = clone $exponent;
  432. }
  433. foreach ($this->coefficients as $coefficient) {
  434. $this->coefficients[] = clone $coefficient;
  435. }
  436. return true;
  437. }
  438. $components = parent::load($key, $type);
  439. if ($components === false) {
  440. return false;
  441. }
  442. $this->modulus = $components['modulus'];
  443. $this->k = $this->modulus->getLengthInBytes();
  444. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  445. if (isset($components['primes'])) {
  446. $this->primes = $components['primes'];
  447. $this->exponents = $components['exponents'];
  448. $this->coefficients = $components['coefficients'];
  449. $this->publicExponent = $components['publicExponent'];
  450. } else {
  451. $this->primes = [];
  452. $this->exponents = [];
  453. $this->coefficients = [];
  454. $this->publicExponent = false;
  455. }
  456. if ($components['isPublicKey']) {
  457. $this->setPublicKey();
  458. }
  459. return true;
  460. }
  461. /**
  462. * Returns the private key
  463. *
  464. * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  465. *
  466. * @see self::getPublicKey()
  467. * @access public
  468. * @param string $type optional
  469. * @return mixed
  470. */
  471. public function getPrivateKey($type = 'PKCS8')
  472. {
  473. $type = self::validatePlugin('Keys', $type, 'savePrivateKey');
  474. if ($type === false) {
  475. return false;
  476. }
  477. if (empty($this->primes)) {
  478. return false;
  479. }
  480. return $type::savePrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients, $this->password);
  481. /*
  482. $key = $type::savePrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients, $this->password);
  483. if ($key !== false || count($this->primes) == 2) {
  484. return $key;
  485. }
  486. $nSize = $this->getSize() >> 1;
  487. $primes = [1 => clone self::$one, clone self::$one];
  488. $i = 1;
  489. foreach ($this->primes as $prime) {
  490. $primes[$i] = $primes[$i]->multiply($prime);
  491. if ($primes[$i]->getLength() >= $nSize) {
  492. $i++;
  493. }
  494. }
  495. $exponents = [];
  496. $coefficients = [2 => $primes[2]->modInverse($primes[1])];
  497. foreach ($primes as $i => $prime) {
  498. $temp = $prime->subtract(self::$one);
  499. $exponents[$i] = $this->modulus->modInverse($temp);
  500. }
  501. return $type::savePrivateKey($this->modulus, $this->publicExponent, $this->exponent, $primes, $exponents, $coefficients, $this->password);
  502. */
  503. }
  504. /**
  505. * Returns a minimalistic private key
  506. *
  507. * Returns the private key without the prime number constituants. Structurally identical to a public key that
  508. * hasn't been set as the public key
  509. *
  510. * @see self::getPrivateKey()
  511. * @access private
  512. * @param string $type optional
  513. * @return mixed
  514. */
  515. protected function getPrivatePublicKey($type = 'PKCS8')
  516. {
  517. $type = self::validatePlugin('Keys', $type, 'savePublicKey');
  518. if ($type === false) {
  519. return false;
  520. }
  521. if (empty($this->modulus) || empty($this->exponent)) {
  522. return false;
  523. }
  524. $oldFormat = $this->publicKeyFormat;
  525. $this->publicKeyFormat = $type;
  526. $temp = $type::savePublicKey($this->modulus, $this->exponent);
  527. $this->publicKeyFormat = $oldFormat;
  528. return $temp;
  529. }
  530. /**
  531. * Returns the key size
  532. *
  533. * More specifically, this returns the size of the modulo in bits.
  534. *
  535. * @access public
  536. * @return int
  537. */
  538. public function getLength()
  539. {
  540. return !isset($this->modulus) ? 0 : $this->modulus->getLength();
  541. }
  542. /**
  543. * Defines the public key
  544. *
  545. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  546. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  547. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  548. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  549. * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used
  550. * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being
  551. * public.
  552. *
  553. * Do note that when a new key is loaded the index will be cleared.
  554. *
  555. * Returns true on success, false on failure
  556. *
  557. * @see self::getPublicKey()
  558. * @access public
  559. * @param string $key optional
  560. * @param int $type optional
  561. * @return bool
  562. */
  563. public function setPublicKey($key = false, $type = false)
  564. {
  565. // if a public key has already been loaded return false
  566. if (!empty($this->publicExponent)) {
  567. return false;
  568. }
  569. if ($key === false && !empty($this->modulus)) {
  570. $this->publicExponent = $this->exponent;
  571. return true;
  572. }
  573. $components = parent::setPublicKey($key, $type);
  574. if ($components === false) {
  575. return false;
  576. }
  577. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  578. $this->modulus = $components['modulus'];
  579. $this->exponent = $this->publicExponent = $components['publicExponent'];
  580. return true;
  581. }
  582. $this->publicExponent = $components['publicExponent'];
  583. return true;
  584. }
  585. /**
  586. * Defines the private key
  587. *
  588. * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force
  589. * phpseclib to treat the key as a private key. This function will do that.
  590. *
  591. * Do note that when a new key is loaded the index will be cleared.
  592. *
  593. * Returns true on success, false on failure
  594. *
  595. * @see self::getPublicKey()
  596. * @access public
  597. * @param string $key optional
  598. * @param int $type optional
  599. * @return bool
  600. */
  601. public function setPrivateKey($key = false, $type = false)
  602. {
  603. if ($key === false && !empty($this->publicExponent)) {
  604. $this->publicExponent = false;
  605. return true;
  606. }
  607. $rsa = new RSA();
  608. if (!$rsa->load($key, $type)) {
  609. return false;
  610. }
  611. $rsa->publicExponent = false;
  612. // don't overwrite the old key if the new key is invalid
  613. $this->load($rsa);
  614. return true;
  615. }
  616. /**
  617. * Returns the public key
  618. *
  619. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  620. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  621. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  622. *
  623. * @see self::getPrivateKey()
  624. * @access public
  625. * @param string $type optional
  626. * @return mixed
  627. */
  628. public function getPublicKey($type = 'PKCS8')
  629. {
  630. $type = self::validatePlugin('Keys', $type, 'savePublicKey');
  631. if ($type === false) {
  632. return false;
  633. }
  634. if (empty($this->modulus) || empty($this->publicExponent)) {
  635. return false;
  636. }
  637. return $type::savePublicKey($this->modulus, $this->publicExponent);
  638. }
  639. /**
  640. * __toString() magic method
  641. *
  642. * @access public
  643. * @return string
  644. */
  645. public function __toString()
  646. {
  647. try {
  648. $key = $this->getPrivateKey($this->privateKeyFormat);
  649. if (is_string($key)) {
  650. return $key;
  651. }
  652. $key = $this->getPrivatePublicKey($this->publicKeyFormat);
  653. return is_string($key) ? $key : '';
  654. } catch (\Exception $e) {
  655. return '';
  656. }
  657. }
  658. /**
  659. * Determines which hashing function should be used
  660. *
  661. * Used with signature production / verification and (if the encryption mode is self::PADDING_OAEP) encryption and
  662. * decryption.
  663. *
  664. * @access public
  665. * @param string $hash
  666. */
  667. public function setHash($hash)
  668. {
  669. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  670. switch (strtolower($hash)) {
  671. case 'md2':
  672. case 'md5':
  673. case 'sha1':
  674. case 'sha256':
  675. case 'sha384':
  676. case 'sha512':
  677. case 'sha224':
  678. case 'sha512/224':
  679. case 'sha512/256':
  680. $this->hash = new Hash($hash);
  681. $this->hashName = $hash;
  682. break;
  683. default:
  684. throw new UnsupportedAlgorithmException(
  685. 'The only supported hash algorithms are: md2, md5, sha1, sha256, sha384, sha512, sha224, sha512/224, sha512/256'
  686. );
  687. }
  688. $this->hLen = $this->hash->getLengthInBytes();
  689. }
  690. /**
  691. * Determines which hashing function should be used for the mask generation function
  692. *
  693. * The mask generation function is used by self::PADDING_OAEP and self::PADDING_PSS and although it's
  694. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  695. *
  696. * @access public
  697. * @param string $hash
  698. */
  699. public function setMGFHash($hash)
  700. {
  701. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  702. switch ($hash) {
  703. case 'md2':
  704. case 'md5':
  705. case 'sha1':
  706. case 'sha256':
  707. case 'sha384':
  708. case 'sha512':
  709. case 'sha224':
  710. case 'sha512/224':
  711. case 'sha512/256':
  712. $this->mgfHash = new Hash($hash);
  713. break;
  714. default:
  715. $this->mgfHash = new Hash('sha256');
  716. }
  717. $this->mgfHLen = $this->mgfHash->getLengthInBytes();
  718. }
  719. /**
  720. * Determines the salt length
  721. *
  722. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  723. *
  724. * Typical salt lengths in octets are hLen (the length of the output
  725. * of the hash function Hash) and 0.
  726. *
  727. * @access public
  728. * @param int $format
  729. */
  730. public function setSaltLength($sLen)
  731. {
  732. $this->sLen = $sLen;
  733. }
  734. /**
  735. * Integer-to-Octet-String primitive
  736. *
  737. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  738. *
  739. * @access private
  740. * @param bool|\phpseclib\Math\BigInteger $x
  741. * @param int $xLen
  742. * @return bool|string
  743. */
  744. private function i2osp($x, $xLen)
  745. {
  746. if ($x === false) {
  747. return false;
  748. }
  749. $x = $x->toBytes();
  750. if (strlen($x) > $xLen) {
  751. return false;
  752. }
  753. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  754. }
  755. /**
  756. * Octet-String-to-Integer primitive
  757. *
  758. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  759. *
  760. * @access private
  761. * @param string $x
  762. * @return \phpseclib\Math\BigInteger
  763. */
  764. private function os2ip($x)
  765. {
  766. return new BigInteger($x, 256);
  767. }
  768. /**
  769. * Exponentiate with or without Chinese Remainder Theorem
  770. *
  771. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  772. *
  773. * @access private
  774. * @param \phpseclib\Math\BigInteger $x
  775. * @return \phpseclib\Math\BigInteger
  776. */
  777. private function exponentiate($x)
  778. {
  779. switch (true) {
  780. case empty($this->primes):
  781. case $this->primes[1]->equals(self::$zero):
  782. case empty($this->coefficients):
  783. case $this->coefficients[2]->equals(self::$zero):
  784. case empty($this->exponents):
  785. case $this->exponents[1]->equals(self::$zero):
  786. return $x->modPow($this->exponent, $this->modulus);
  787. }
  788. $num_primes = count($this->primes);
  789. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  790. $m_i = [
  791. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  792. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  793. ];
  794. $h = $m_i[1]->subtract($m_i[2]);
  795. $h = $h->multiply($this->coefficients[2]);
  796. list(, $h) = $h->divide($this->primes[1]);
  797. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  798. $r = $this->primes[1];
  799. for ($i = 3; $i <= $num_primes; $i++) {
  800. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  801. $r = $r->multiply($this->primes[$i - 1]);
  802. $h = $m_i->subtract($m);
  803. $h = $h->multiply($this->coefficients[$i]);
  804. list(, $h) = $h->divide($this->primes[$i]);
  805. $m = $m->add($r->multiply($h));
  806. }
  807. } else {
  808. $smallest = $this->primes[1];
  809. for ($i = 2; $i <= $num_primes; $i++) {
  810. if ($smallest->compare($this->primes[$i]) > 0) {
  811. $smallest = $this->primes[$i];
  812. }
  813. }
  814. $r = BigInteger::randomRange(self::$one, $smallest->subtract(self::$one));
  815. $m_i = [
  816. 1 => $this->blind($x, $r, 1),
  817. 2 => $this->blind($x, $r, 2)
  818. ];
  819. $h = $m_i[1]->subtract($m_i[2]);
  820. $h = $h->multiply($this->coefficients[2]);
  821. list(, $h) = $h->divide($this->primes[1]);
  822. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  823. $r = $this->primes[1];
  824. for ($i = 3; $i <= $num_primes; $i++) {
  825. $m_i = $this->blind($x, $r, $i);
  826. $r = $r->multiply($this->primes[$i - 1]);
  827. $h = $m_i->subtract($m);
  828. $h = $h->multiply($this->coefficients[$i]);
  829. list(, $h) = $h->divide($this->primes[$i]);
  830. $m = $m->add($r->multiply($h));
  831. }
  832. }
  833. return $m;
  834. }
  835. /**
  836. * Performs RSA Blinding
  837. *
  838. * Protects against timing attacks by employing RSA Blinding.
  839. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  840. *
  841. * @access private
  842. * @param \phpseclib\Math\BigInteger $x
  843. * @param \phpseclib\Math\BigInteger $r
  844. * @param int $i
  845. * @return \phpseclib\Math\BigInteger
  846. */
  847. private function blind($x, $r, $i)
  848. {
  849. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  850. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  851. $r = $r->modInverse($this->primes[$i]);
  852. $x = $x->multiply($r);
  853. list(, $x) = $x->divide($this->primes[$i]);
  854. return $x;
  855. }
  856. /**
  857. * RSAEP
  858. *
  859. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  860. *
  861. * @access private
  862. * @param \phpseclib\Math\BigInteger $m
  863. * @return bool|\phpseclib\Math\BigInteger
  864. */
  865. private function rsaep($m)
  866. {
  867. if ($m->compare(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
  868. return false;
  869. }
  870. return $this->exponentiate($m);
  871. }
  872. /**
  873. * RSADP
  874. *
  875. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  876. *
  877. * @access private
  878. * @param \phpseclib\Math\BigInteger $c
  879. * @return bool|\phpseclib\Math\BigInteger
  880. */
  881. private function rsadp($c)
  882. {
  883. if ($c->compare(self::$zero) < 0 || $c->compare($this->modulus) > 0) {
  884. return false;
  885. }
  886. return $this->exponentiate($c);
  887. }
  888. /**
  889. * RSASP1
  890. *
  891. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  892. *
  893. * @access private
  894. * @param \phpseclib\Math\BigInteger $m
  895. * @return bool|\phpseclib\Math\BigInteger
  896. */
  897. private function rsasp1($m)
  898. {
  899. if ($m->compare(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
  900. return false;
  901. }
  902. return $this->exponentiate($m);
  903. }
  904. /**
  905. * RSAVP1
  906. *
  907. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  908. *
  909. * @access private
  910. * @param \phpseclib\Math\BigInteger $s
  911. * @return bool|\phpseclib\Math\BigInteger
  912. */
  913. private function rsavp1($s)
  914. {
  915. if ($s->compare(self::$zero) < 0 || $s->compare($this->modulus) > 0) {
  916. return false;
  917. }
  918. return $this->exponentiate($s);
  919. }
  920. /**
  921. * MGF1
  922. *
  923. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  924. *
  925. * @access private
  926. * @param string $mgfSeed
  927. * @param int $mgfLen
  928. * @return string
  929. */
  930. private function mgf1($mgfSeed, $maskLen)
  931. {
  932. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  933. $t = '';
  934. $count = ceil($maskLen / $this->mgfHLen);
  935. for ($i = 0; $i < $count; $i++) {
  936. $c = pack('N', $i);
  937. $t.= $this->mgfHash->hash($mgfSeed . $c);
  938. }
  939. return substr($t, 0, $maskLen);
  940. }
  941. /**
  942. * RSAES-OAEP-ENCRYPT
  943. *
  944. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  945. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  946. *
  947. * @access private
  948. * @param string $m
  949. * @param string $l
  950. * @throws \OutOfBoundsException if strlen($m) > $this->k - 2 * $this->hLen - 2
  951. * @return string
  952. */
  953. private function rsaes_oaep_encrypt($m, $l = '')
  954. {
  955. $mLen = strlen($m);
  956. // Length checking
  957. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  958. // be output.
  959. if ($mLen > $this->k - 2 * $this->hLen - 2) {
  960. throw new \OutOfBoundsException('Message too long');
  961. }
  962. // EME-OAEP encoding
  963. $lHash = $this->hash->hash($l);
  964. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  965. $db = $lHash . $ps . chr(1) . $m;
  966. $seed = Random::string($this->hLen);
  967. $dbMask = $this->mgf1($seed, $this->k - $this->hLen - 1);
  968. $maskedDB = $db ^ $dbMask;
  969. $seedMask = $this->mgf1($maskedDB, $this->hLen);
  970. $maskedSeed = $seed ^ $seedMask;
  971. $em = chr(0) . $maskedSeed . $maskedDB;
  972. // RSA encryption
  973. $m = $this->os2ip($em);
  974. $c = $this->rsaep($m);
  975. $c = $this->i2osp($c, $this->k);
  976. // Output the ciphertext C
  977. return $c;
  978. }
  979. /**
  980. * RSAES-OAEP-DECRYPT
  981. *
  982. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  983. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  984. *
  985. * Note. Care must be taken to ensure that an opponent cannot
  986. * distinguish the different error conditions in Step 3.g, whether by
  987. * error message or timing, or, more generally, learn partial
  988. * information about the encoded message EM. Otherwise an opponent may
  989. * be able to obtain useful information about the decryption of the
  990. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  991. * observed by Manger [36].
  992. *
  993. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  994. *
  995. * Both the encryption and the decryption operations of RSAES-OAEP take
  996. * the value of a label L as input. In this version of PKCS #1, L is
  997. * the empty string; other uses of the label are outside the scope of
  998. * this document.
  999. *
  1000. * @access private
  1001. * @param string $c
  1002. * @param string $l
  1003. * @return bool|string
  1004. */
  1005. private function rsaes_oaep_decrypt($c, $l = '')
  1006. {
  1007. // Length checking
  1008. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1009. // be output.
  1010. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  1011. return false;
  1012. }
  1013. // RSA decryption
  1014. $c = $this->os2ip($c);
  1015. $m = $this->rsadp($c);
  1016. $em = $this->i2osp($m, $this->k);
  1017. if ($em === false) {
  1018. return false;
  1019. }
  1020. // EME-OAEP decoding
  1021. $lHash = $this->hash->hash($l);
  1022. $y = ord($em[0]);
  1023. $maskedSeed = substr($em, 1, $this->hLen);
  1024. $maskedDB = substr($em, $this->hLen + 1);
  1025. $seedMask = $this->mgf1($maskedDB, $this->hLen);
  1026. $seed = $maskedSeed ^ $seedMask;
  1027. $dbMask = $this->mgf1($seed, $this->k - $this->hLen - 1);
  1028. $db = $maskedDB ^ $dbMask;
  1029. $lHash2 = substr($db, 0, $this->hLen);
  1030. $m = substr($db, $this->hLen);
  1031. if (!Strings::equals($lHash, $lHash2)) {
  1032. return false;
  1033. }
  1034. $m = ltrim($m, chr(0));
  1035. if (ord($m[0]) != 1) {
  1036. return false;
  1037. }
  1038. // Output the message M
  1039. return substr($m, 1);
  1040. }
  1041. /**
  1042. * Raw Encryption / Decryption
  1043. *
  1044. * Doesn't use padding and is not recommended.
  1045. *
  1046. * @access private
  1047. * @param string $m
  1048. * @return bool|string
  1049. * @throws \OutOfBoundsException if strlen($m) > $this->k
  1050. */
  1051. private function raw_encrypt($m)
  1052. {
  1053. if (strlen($m) > $this->k) {
  1054. throw new \OutOfBoundsException('Message too long');
  1055. }
  1056. $temp = $this->os2ip($m);
  1057. $temp = $this->rsaep($temp);
  1058. return $this->i2osp($temp, $this->k);
  1059. }
  1060. /**
  1061. * RSAES-PKCS1-V1_5-ENCRYPT
  1062. *
  1063. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  1064. *
  1065. * @access private
  1066. * @param string $m
  1067. * @param bool $pkcs15_compat optional
  1068. * @throws \OutOfBoundsException if strlen($m) > $this->k - 11
  1069. * @return bool|string
  1070. */
  1071. private function rsaes_pkcs1_v1_5_encrypt($m, $pkcs15_compat = false)
  1072. {
  1073. $mLen = strlen($m);
  1074. // Length checking
  1075. if ($mLen > $this->k - 11) {
  1076. throw new \OutOfBoundsException('Message too long');
  1077. }
  1078. // EME-PKCS1-v1_5 encoding
  1079. $psLen = $this->k - $mLen - 3;
  1080. $ps = '';
  1081. while (strlen($ps) != $psLen) {
  1082. $temp = Random::string($psLen - strlen($ps));
  1083. $temp = str_replace("\x00", '', $temp);
  1084. $ps.= $temp;
  1085. }
  1086. $type = 2;
  1087. // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  1088. if ($pkcs15_compat && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
  1089. $type = 1;
  1090. // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  1091. $ps = str_repeat("\xFF", $psLen);
  1092. }
  1093. $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  1094. // RSA encryption
  1095. $m = $this->os2ip($em);
  1096. $c = $this->rsaep($m);
  1097. $c = $this->i2osp($c, $this->k);
  1098. // Output the ciphertext C
  1099. return $c;
  1100. }
  1101. /**
  1102. * RSAES-PKCS1-V1_5-DECRYPT
  1103. *
  1104. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  1105. *
  1106. * For compatibility purposes, this function departs slightly from the description given in RFC3447.
  1107. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  1108. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  1109. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  1110. * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
  1111. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  1112. *
  1113. * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt
  1114. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  1115. * not private key encrypted ciphertext's.
  1116. *
  1117. * @access private
  1118. * @param string $c
  1119. * @return bool|string
  1120. */
  1121. private function rsaes_pkcs1_v1_5_decrypt($c)
  1122. {
  1123. // Length checking
  1124. if (strlen($c) != $this->k) { // or if k < 11
  1125. return false;
  1126. }
  1127. // RSA decryption
  1128. $c = $this->os2ip($c);
  1129. $m = $this->rsadp($c);
  1130. $em = $this->i2osp($m, $this->k);
  1131. if ($em === false) {
  1132. return false;
  1133. }
  1134. // EME-PKCS1-v1_5 decoding
  1135. if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  1136. return false;
  1137. }
  1138. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  1139. $m = substr($em, strlen($ps) + 3);
  1140. if (strlen($ps) < 8) {
  1141. return false;
  1142. }
  1143. // Output M
  1144. return $m;
  1145. }
  1146. /**
  1147. * EMSA-PSS-ENCODE
  1148. *
  1149. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  1150. *
  1151. * @access private
  1152. * @param string $m
  1153. * @throws \RuntimeException on encoding error
  1154. * @param int $emBits
  1155. */
  1156. private function emsa_pss_encode($m, $emBits)
  1157. {
  1158. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1159. // be output.
  1160. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  1161. $sLen = $this->sLen !== null ? $this->sLen : $this->hLen;
  1162. $mHash = $this->hash->hash($m);
  1163. if ($emLen < $this->hLen + $sLen + 2) {
  1164. return false;
  1165. }
  1166. $salt = Random::string($sLen);
  1167. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1168. $h = $this->hash->hash($m2);
  1169. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  1170. $db = $ps . chr(1) . $salt;
  1171. $dbMask = $this->mgf1($h, $emLen - $this->hLen - 1);
  1172. $maskedDB = $db ^ $dbMask;
  1173. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  1174. $em = $maskedDB . $h . chr(0xBC);
  1175. return $em;
  1176. }
  1177. /**
  1178. * EMSA-PSS-VERIFY
  1179. *
  1180. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  1181. *
  1182. * @access private
  1183. * @param string $m
  1184. * @param string $em
  1185. * @param int $emBits
  1186. * @return string
  1187. */
  1188. private function emsa_pss_verify($m, $em, $emBits)
  1189. {
  1190. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1191. // be output.
  1192. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  1193. $sLen = $this->sLen !== null ? $this->sLen : $this->hLen;
  1194. $mHash = $this->hash->hash($m);
  1195. if ($emLen < $this->hLen + $sLen + 2) {
  1196. return false;
  1197. }
  1198. if ($em[strlen($em) - 1] != chr(0xBC)) {
  1199. return false;
  1200. }
  1201. $maskedDB = substr($em, 0, -$this->hLen - 1);
  1202. $h = substr($em, -$this->hLen - 1, $this->hLen);
  1203. $temp = chr(0xFF << ($emBits & 7));
  1204. if ((~$maskedDB[0] & $temp) != $temp) {
  1205. return false;
  1206. }
  1207. $dbMask = $this->mgf1($h, $emLen - $this->hLen - 1);
  1208. $db = $maskedDB ^ $dbMask;
  1209. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  1210. $temp = $emLen - $this->hLen - $sLen - 2;
  1211. if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  1212. return false;
  1213. }
  1214. $salt = substr($db, $temp + 1); // should be $sLen long
  1215. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1216. $h2 = $this->hash->hash($m2);
  1217. return Strings::equals($h, $h2);
  1218. }
  1219. /**
  1220. * RSASSA-PSS-SIGN
  1221. *
  1222. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  1223. *
  1224. * @access private
  1225. * @param string $m
  1226. * @return bool|string
  1227. */
  1228. private function rsassa_pss_sign($m)
  1229. {
  1230. // EMSA-PSS encoding
  1231. $em = $this->emsa_pss_encode($m, 8 * $this->k - 1);
  1232. // RSA signature
  1233. $m = $this->os2ip($em);
  1234. $s = $this->rsasp1($m);
  1235. $s = $this->i2osp($s, $this->k);
  1236. // Output the signature S
  1237. return $s;
  1238. }
  1239. /**
  1240. * RSASSA-PSS-VERIFY
  1241. *
  1242. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  1243. *
  1244. * @access private
  1245. * @param string $m
  1246. * @param string $s
  1247. * @return bool|string
  1248. */
  1249. private function rsassa_pss_verify($m, $s)
  1250. {
  1251. // Length checking
  1252. if (strlen($s) != $this->k) {
  1253. return false;
  1254. }
  1255. // RSA verification
  1256. $modBits = 8 * $this->k;
  1257. $s2 = $this->os2ip($s);
  1258. $m2 = $this->rsavp1($s2);
  1259. $em = $this->i2osp($m2, $modBits >> 3);
  1260. if ($em === false) {
  1261. return false;
  1262. }
  1263. // EMSA-PSS verification
  1264. return $this->emsa_pss_verify($m, $em, $modBits - 1);
  1265. }
  1266. /**
  1267. * EMSA-PKCS1-V1_5-ENCODE
  1268. *
  1269. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  1270. *
  1271. * @access private
  1272. * @param string $m
  1273. * @param int $emLen
  1274. * @throws \LengthException if the intended encoded message length is too short
  1275. * @return string
  1276. */
  1277. private function emsa_pkcs1_v1_5_encode($m, $emLen)
  1278. {
  1279. $h = $this->hash->hash($m);
  1280. // see http://tools.ietf.org/html/rfc3447#page-43
  1281. switch ($this->hashName) {
  1282. case 'md2':
  1283. $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10";
  1284. break;
  1285. case 'md5':
  1286. $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10";
  1287. break;
  1288. case 'sha1':
  1289. $t = "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14";
  1290. break;
  1291. case 'sha256':
  1292. $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20";
  1293. break;
  1294. case 'sha384':
  1295. $t = "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30";
  1296. break;
  1297. case 'sha512':
  1298. $t = "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40";
  1299. break;
  1300. // from https://www.emc.com/collateral/white-papers/h11300-pkcs-1v2-2-rsa-cryptography-standard-wp.pdf#page=40
  1301. case 'sha224':
  1302. $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c";
  1303. break;
  1304. case 'sha512/224':
  1305. $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x05\x05\x00\x04\x1c";
  1306. break;
  1307. case 'sha512/256':
  1308. $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x06\x05\x00\x04\x20";
  1309. }
  1310. $t.= $h;
  1311. $tLen = strlen($t);
  1312. if ($emLen < $tLen + 11) {
  1313. throw new \LengthException('Intended encoded message length too short');
  1314. }
  1315. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  1316. $em = "\0\1$ps\0$t";
  1317. return $em;
  1318. }
  1319. /**
  1320. * RSASSA-PKCS1-V1_5-SIGN
  1321. *
  1322. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  1323. *
  1324. * @access private
  1325. * @param string $m
  1326. * @throws \LengthException if the RSA modulus is too short
  1327. * @return bool|string
  1328. */
  1329. private function rsassa_pkcs1_v1_5_sign($m)
  1330. {
  1331. // EMSA-PKCS1-v1_5 encoding
  1332. // If the encoding operation outputs "intended encoded message length too short," output "RSA modulus
  1333. // too short" and stop.
  1334. try {
  1335. $em = $this->emsa_pkcs1_v1_5_encode($m, $this->k);
  1336. } catch (\LengthException $e) {
  1337. throw new \LengthException('RSA modulus too short');
  1338. }
  1339. // RSA signature
  1340. $m = $this->os2ip($em);
  1341. $s = $this->rsasp1($m);
  1342. $s = $this->i2osp($s, $this->k);
  1343. // Output the signature S
  1344. return $s;
  1345. }
  1346. /**
  1347. * RSASSA-PKCS1-V1_5-VERIFY
  1348. *
  1349. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  1350. *
  1351. * @access private
  1352. * @param string $m
  1353. * @param string $s
  1354. * @throws \LengthException if the RSA modulus is too short
  1355. * @return bool
  1356. */
  1357. private function rsassa_pkcs1_v1_5_verify($m, $s)
  1358. {
  1359. // Length checking
  1360. if (strlen($s) != $this->k) {
  1361. return false;
  1362. }
  1363. // RSA verification
  1364. $s = $this->os2ip($s);
  1365. $m2 = $this->rsavp1($s);
  1366. $em = $this->i2osp($m2, $this->k);
  1367. if ($em === false) {
  1368. return false;
  1369. }
  1370. // EMSA-PKCS1-v1_5 encoding
  1371. // If the encoding operation outputs "intended encoded message length too short," output "RSA modulus
  1372. // too short" and stop.
  1373. try {
  1374. $em2 = $this->emsa_pkcs1_v1_5_encode($m, $this->k);
  1375. } catch (\LengthException $e) {
  1376. throw new \LengthException('RSA modulus too short');
  1377. }
  1378. // Compare
  1379. return Strings::equals($em, $em2);
  1380. }
  1381. /**
  1382. * RSASSA-PKCS1-V1_5-VERIFY (relaxed matching)
  1383. *
  1384. * Per {@link http://tools.ietf.org/html/rfc3447#page-43 RFC3447#page-43} PKCS1 v1.5
  1385. * specified the use BER encoding rather than DER encoding that PKCS1 v2.0 specified.
  1386. * This means that under rare conditions you can have a perfectly valid v1.5 signature
  1387. * that fails to validate with _rsassa_pkcs1_v1_5_verify(). PKCS1 v2.1 also recommends
  1388. * that if you're going to validate these types of signatures you "should indicate
  1389. * whether the underlying BER encoding is a DER encoding and hence whether the signature
  1390. * is valid with respect to the specification given in [PKCS1 v2.0+]". so if you do
  1391. * $rsa->getLastPadding() and get RSA::PADDING_RELAXED_PKCS1 back instead of
  1392. * RSA::PADDING_PKCS1... that means BER encoding was used.
  1393. *
  1394. * @access private
  1395. * @param string $m
  1396. * @param string $s
  1397. * @return bool
  1398. */
  1399. private function rsassa_pkcs1_v1_5_relaxed_verify($m, $s)
  1400. {
  1401. // Length checking
  1402. if (strlen($s) != $this->k) {
  1403. return false;
  1404. }
  1405. // RSA verification
  1406. $s = $this->os2ip($s);
  1407. $m2 = $this->rsavp1($s);
  1408. if ($m2 === false) {
  1409. return false;
  1410. }
  1411. $em = $this->i2osp($m2, $this->k);
  1412. if ($em === false) {
  1413. return false;
  1414. }
  1415. if (Strings::shift($em, 2) != "\0\1") {
  1416. return false;
  1417. }
  1418. $em = ltrim($em, "\xFF");
  1419. if (Strings::shift($em) != "\0") {
  1420. return false;
  1421. }
  1422. $decoded = ASN1::decodeBER($em);
  1423. if (!is_array($decoded) || empty($decoded[0]) || strlen($em) > $decoded[0]['length']) {
  1424. return false;
  1425. }
  1426. static $oids;
  1427. if (!isset($oids)) {
  1428. $oids = [
  1429. '1.2.840.113549.2.2' => 'md2',
  1430. '1.2.840.113549.2.4' => 'md4', // from PKCS1 v1.5
  1431. '1.2.840.113549.2.5' => 'md5',
  1432. '1.3.14.3.2.26' => 'id-sha1',
  1433. '2.16.840.1.101.3.4.2.1' => 'id-sha256',
  1434. '2.16.840.1.101.3.4.2.2' => 'id-sha384',
  1435. '2.16.840.1.101.3.4.2.3' => 'id-sha512',
  1436. // from PKCS1 v2.2
  1437. '2.16.840.1.101.3.4.2.4' => 'id-sha224',
  1438. '2.16.840.1.101.3.4.2.5' => 'id-sha512/224',
  1439. '2.16.840.1.101.3.4.2.6' => 'id-sha512/256',
  1440. ];
  1441. ASN1::loadOIDs($oids);
  1442. }
  1443. $decoded = ASN1::asn1map($decoded[0], DigestInfo::MAP);
  1444. if (!isset($decoded) || $decoded === false) {
  1445. return false;
  1446. }
  1447. if (!in_array($decoded['digestAlgorithm']['algorithm'], $oids)) {
  1448. return false;
  1449. }
  1450. $hash = $decoded['digestAlgorithm']['algorithm'];
  1451. $hash = substr($hash, 0, 3) == 'id-' ?
  1452. substr($hash, 3) :
  1453. $hash;
  1454. $hash = new Hash($hash);
  1455. $em = $hash->hash($m);
  1456. $em2 = $decoded['digest'];
  1457. return Strings::equals($em, $em2);
  1458. }
  1459. /**
  1460. * Encryption
  1461. *
  1462. * Both self::PADDING_OAEP and self::PADDING_PKCS1 both place limits on how long $plaintext can be.
  1463. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  1464. * be concatenated together.
  1465. *
  1466. * @see self::decrypt()
  1467. * @access public
  1468. * @param string $plaintext
  1469. * @param int $padding optional
  1470. * @return bool|string
  1471. * @throws \LengthException if the RSA modulus is too short
  1472. */
  1473. public function encrypt($plaintext, $padding = self::PADDING_OAEP)
  1474. {
  1475. switch ($padding) {
  1476. case self::PADDING_NONE:
  1477. return $this->raw_encrypt($plaintext);
  1478. case self::PADDING_PKCS15_COMPAT:
  1479. case self::PADDING_PKCS1:
  1480. return $this->rsaes_pkcs1_v1_5_encrypt($plaintext, $padding == self::PADDING_PKCS15_COMPAT);
  1481. //case self::PADDING_OAEP:
  1482. default:
  1483. return $this->rsaes_oaep_encrypt($plaintext);
  1484. }
  1485. }
  1486. /**
  1487. * Decryption
  1488. *
  1489. * @see self::encrypt()
  1490. * @access public
  1491. * @param string $plaintext
  1492. * @param int $padding optional
  1493. * @return bool|string
  1494. */
  1495. public function decrypt($ciphertext, $padding = self::PADDING_OAEP)
  1496. {
  1497. switch ($padding) {
  1498. case self::PADDING_NONE:
  1499. return $this->raw_encrypt($ciphertext);
  1500. case self::PADDING_PKCS1:
  1501. return $this->rsaes_pkcs1_v1_5_decrypt($ciphertext);
  1502. //case self::PADDING_OAEP:
  1503. default:
  1504. return $this->rsaes_oaep_decrypt($ciphertext);
  1505. }
  1506. }
  1507. /**
  1508. * Create a signature
  1509. *
  1510. * @see self::verify()
  1511. * @access public
  1512. * @param string $message
  1513. * @param int $padding optional
  1514. * @return string
  1515. */
  1516. public function sign($message, $padding = self::PADDING_PSS)
  1517. {
  1518. if (empty($this->modulus) || empty($this->exponent)) {
  1519. return false;
  1520. }
  1521. switch ($padding) {
  1522. case self::PADDING_PKCS1:
  1523. case self::PADDING_RELAXED_PKCS1:
  1524. return $this->rsassa_pkcs1_v1_5_sign($message);
  1525. //case self::PADDING_PSS:
  1526. default:
  1527. return $this->rsassa_pss_sign($message);
  1528. }
  1529. }
  1530. /**
  1531. * Verifies a signature
  1532. *
  1533. * @see self::sign()
  1534. * @access public
  1535. * @param string $message
  1536. * @param string $signature
  1537. * @param int $padding optional
  1538. * @return bool
  1539. */
  1540. public function verify($message, $signature, $padding = self::PADDING_PSS)
  1541. {
  1542. if (empty($this->modulus) || empty($this->exponent)) {
  1543. return false;
  1544. }
  1545. switch ($padding) {
  1546. case self::PADDING_RELAXED_PKCS1:
  1547. return $this->rsassa_pkcs1_v1_5_relaxed_verify($message, $signature);
  1548. case self::PADDING_PKCS1:
  1549. return $this->rsassa_pkcs1_v1_5_verify($message, $signature);
  1550. //case self::PADDING_PSS:
  1551. default:
  1552. return $this->rsassa_pss_verify($message, $signature);
  1553. }
  1554. }
  1555. }