RSA.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251
  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. /**
  49. * Pure-PHP PKCS#1 compliant implementation of RSA.
  50. *
  51. * @package RSA
  52. * @author Jim Wigginton <terrafrost@php.net>
  53. * @access public
  54. */
  55. class RSA
  56. {
  57. /**#@+
  58. * @access public
  59. * @see self::encrypt()
  60. * @see self::decrypt()
  61. */
  62. /**
  63. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  64. * (OAEP) for encryption / decryption.
  65. *
  66. * Uses sha256 by default
  67. *
  68. * @see self::setHash()
  69. * @see self::setMGFHash()
  70. */
  71. const PADDING_OAEP = 1;
  72. /**
  73. * Use PKCS#1 padding.
  74. *
  75. * Although self::PADDING_OAEP / self::PADDING_PSS offers more security, including PKCS#1 padding is necessary for purposes of backwards
  76. * compatibility with protocols (like SSH-1) written before OAEP's introduction.
  77. */
  78. const PADDING_PKCS1 = 2;
  79. /**
  80. * Do not use any padding
  81. *
  82. * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy
  83. * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc.
  84. */
  85. const PADDING_NONE = 3;
  86. /**
  87. * Use PKCS#1 padding with PKCS1 v1.5 compatability
  88. *
  89. * A PKCS1 v2.1 encrypted message may not successfully decrypt with a PKCS1 v1.5 implementation (such as OpenSSL).
  90. */
  91. const PADDING_PKCS15_COMPAT = 6;
  92. /**#@-*/
  93. /**#@+
  94. * @access public
  95. * @see self::sign()
  96. * @see self::verify()
  97. * @see self::setHash()
  98. */
  99. /**
  100. * Use the Probabilistic Signature Scheme for signing
  101. *
  102. * Uses sha256 and 0 as the salt length
  103. *
  104. * @see self::setSaltLength()
  105. * @see self::setMGFHash()
  106. * @see self::setHash()
  107. */
  108. const PADDING_PSS = 4;
  109. /**
  110. * Use a relaxed version of PKCS#1 padding for signature verification
  111. */
  112. const PADDING_RELAXED_PKCS1 = 5;
  113. /**#@-*/
  114. /**#@+
  115. * @access private
  116. * @see self::createKey()
  117. */
  118. /**
  119. * ASN1 Integer
  120. */
  121. const ASN1_INTEGER = 2;
  122. /**
  123. * ASN1 Bit String
  124. */
  125. const ASN1_BITSTRING = 3;
  126. /**
  127. * ASN1 Octet String
  128. */
  129. const ASN1_OCTETSTRING = 4;
  130. /**
  131. * ASN1 Object Identifier
  132. */
  133. const ASN1_OBJECT = 6;
  134. /**
  135. * ASN1 Sequence (with the constucted bit set)
  136. */
  137. const ASN1_SEQUENCE = 48;
  138. /**#@-*/
  139. /**#@+
  140. * @access private
  141. * @see self::__construct()
  142. */
  143. /**
  144. * To use the pure-PHP implementation
  145. */
  146. const MODE_INTERNAL = 1;
  147. /**
  148. * To use the OpenSSL library
  149. *
  150. * (if enabled; otherwise, the internal implementation will be used)
  151. */
  152. const MODE_OPENSSL = 2;
  153. /**#@-*/
  154. /**
  155. * Precomputed Zero
  156. *
  157. * @var array
  158. * @access private
  159. */
  160. static $zero;
  161. /**
  162. * Precomputed One
  163. *
  164. * @var array
  165. * @access private
  166. */
  167. static $one;
  168. /**
  169. * Private Key Format
  170. *
  171. * @var string
  172. * @access private
  173. */
  174. var $privateKeyFormat = 'PKCS1';
  175. /**
  176. * Public Key Format
  177. *
  178. * @var string
  179. * @access private
  180. */
  181. var $publicKeyFormat = 'PKCS8';
  182. /**
  183. * Modulus (ie. n)
  184. *
  185. * @var \phpseclib\Math\BigInteger
  186. * @access private
  187. */
  188. var $modulus;
  189. /**
  190. * Modulus length
  191. *
  192. * @var \phpseclib\Math\BigInteger
  193. * @access private
  194. */
  195. var $k;
  196. /**
  197. * Exponent (ie. e or d)
  198. *
  199. * @var \phpseclib\Math\BigInteger
  200. * @access private
  201. */
  202. var $exponent;
  203. /**
  204. * Primes for Chinese Remainder Theorem (ie. p and q)
  205. *
  206. * @var array
  207. * @access private
  208. */
  209. var $primes;
  210. /**
  211. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  212. *
  213. * @var array
  214. * @access private
  215. */
  216. var $exponents;
  217. /**
  218. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  219. *
  220. * @var array
  221. * @access private
  222. */
  223. var $coefficients;
  224. /**
  225. * Hash name
  226. *
  227. * @var string
  228. * @access private
  229. */
  230. var $hashName;
  231. /**
  232. * Hash function
  233. *
  234. * @var \phpseclib\Crypt\Hash
  235. * @access private
  236. */
  237. var $hash;
  238. /**
  239. * Length of hash function output
  240. *
  241. * @var int
  242. * @access private
  243. */
  244. var $hLen;
  245. /**
  246. * Length of salt
  247. *
  248. * @var int
  249. * @access private
  250. */
  251. var $sLen;
  252. /**
  253. * Hash function for the Mask Generation Function
  254. *
  255. * @var \phpseclib\Crypt\Hash
  256. * @access private
  257. */
  258. var $mgfHash;
  259. /**
  260. * Length of MGF hash function output
  261. *
  262. * @var int
  263. * @access private
  264. */
  265. var $mgfHLen;
  266. /**
  267. * Public Exponent
  268. *
  269. * @var mixed
  270. * @access private
  271. */
  272. var $publicExponent = false;
  273. /**
  274. * Password
  275. *
  276. * @var string
  277. * @access private
  278. */
  279. var $password = false;
  280. /**
  281. * Loaded File Format
  282. *
  283. * @var string
  284. * @access private
  285. */
  286. var $format = false;
  287. /**
  288. * OpenSSL configuration file name.
  289. *
  290. * Set to null to use system configuration file.
  291. *
  292. * @see self::createKey()
  293. * @var mixed
  294. * @access public
  295. */
  296. static $configFile;
  297. /**
  298. * Supported file formats (lower case)
  299. *
  300. * @see self::_initialize_static_variables()
  301. * @var array
  302. * @access private
  303. */
  304. static $fileFormats = false;
  305. /**
  306. * Supported file formats (original case)
  307. *
  308. * @see self::_initialize_static_variables()
  309. * @var array
  310. * @access private
  311. */
  312. static $origFileFormats = false;
  313. /**
  314. * Initialize static variables
  315. *
  316. * @access private
  317. */
  318. static function _initialize_static_variables()
  319. {
  320. if (!isset(self::$zero)) {
  321. self::$zero= new BigInteger(0);
  322. self::$one = new BigInteger(1);
  323. self::$configFile = __DIR__ . '/../openssl.cnf';
  324. if (self::$fileFormats === false) {
  325. self::$fileFormats = array();
  326. foreach (glob(__DIR__ . '/RSA/*.php') as $file) {
  327. $name = pathinfo($file, PATHINFO_FILENAME);
  328. $type = 'phpseclib\Crypt\RSA\\' . $name;
  329. $meta = new \ReflectionClass($type);
  330. if (!$meta->isAbstract()) {
  331. self::$fileFormats[strtolower($name)] = $type;
  332. self::$origFileFormats[] = $name;
  333. }
  334. }
  335. }
  336. }
  337. }
  338. /**
  339. * The constructor
  340. *
  341. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  342. * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  343. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  344. *
  345. * @return \phpseclib\Crypt\RSA
  346. * @access public
  347. */
  348. function __construct()
  349. {
  350. self::_initialize_static_variables();
  351. $this->hash = new Hash('sha256');
  352. $this->hLen = $this->hash->getLength();
  353. $this->hashName = 'sha256';
  354. $this->mgfHash = new Hash('sha256');
  355. $this->mgfHLen = $this->mgfHash->getLength();
  356. }
  357. /**
  358. * Create public / private key pair
  359. *
  360. * Returns an array with the following three elements:
  361. * - 'privatekey': The private key.
  362. * - 'publickey': The public key.
  363. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  364. * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing.
  365. *
  366. * @access public
  367. * @param int $bits
  368. * @param int $timeout
  369. * @param array $p
  370. */
  371. static function createKey($bits = 2048, $timeout = false, $partial = array())
  372. {
  373. self::_initialize_static_variables();
  374. if (!defined('CRYPT_RSA_MODE')) {
  375. switch (true) {
  376. // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
  377. // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger
  378. // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
  379. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'):
  380. define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
  381. break;
  382. case extension_loaded('openssl') && file_exists(self::$configFile):
  383. define('CRYPT_RSA_MODE', self::MODE_OPENSSL);
  384. break;
  385. default:
  386. define('CRYPT_RSA_MODE', self::MODE_INTERNAL);
  387. }
  388. }
  389. if (!defined('CRYPT_RSA_EXPONENT')) {
  390. // http://en.wikipedia.org/wiki/65537_%28number%29
  391. define('CRYPT_RSA_EXPONENT', '65537');
  392. }
  393. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  394. // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
  395. // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
  396. // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then
  397. // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
  398. // generation when there's a chance neither gmp nor OpenSSL are installed)
  399. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  400. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  401. }
  402. // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  403. if (CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) {
  404. $config = array();
  405. if (isset(self::$configFile)) {
  406. $config['config'] = self::$configFile;
  407. }
  408. $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
  409. openssl_pkey_export($rsa, $privatekeystr, null, $config);
  410. $privatekey = new RSA();
  411. $privatekey->load($privatekeystr);
  412. $publickeyarr = openssl_pkey_get_details($rsa);
  413. $publickey = new RSA();
  414. $publickey->load($publickeyarr['key']);
  415. // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  416. while (openssl_error_string() !== false) {
  417. }
  418. return array(
  419. 'privatekey' => $privatekey,
  420. 'publickey' => $publickey,
  421. 'partialkey' => false
  422. );
  423. }
  424. static $e;
  425. if (!isset($e)) {
  426. $e = new BigInteger(CRYPT_RSA_EXPONENT);
  427. }
  428. extract(self::_generateMinMax($bits));
  429. $absoluteMin = $min;
  430. $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
  431. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  432. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  433. $temp = CRYPT_RSA_SMALLEST_PRIME;
  434. } else {
  435. $num_primes = 2;
  436. }
  437. extract(self::_generateMinMax($temp + $bits % $temp));
  438. $finalMax = $max;
  439. extract(self::_generateMinMax($temp));
  440. $n = clone self::$one;
  441. if (!empty($partial)) {
  442. extract(unserialize($partial));
  443. } else {
  444. $exponents = $coefficients = $primes = array();
  445. $lcm = array(
  446. 'top' => clone self::$one,
  447. 'bottom' => false
  448. );
  449. }
  450. $start = time();
  451. $i0 = count($primes) + 1;
  452. do {
  453. for ($i = $i0; $i <= $num_primes; $i++) {
  454. if ($timeout !== false) {
  455. $timeout-= time() - $start;
  456. $start = time();
  457. if ($timeout <= 0) {
  458. return array(
  459. 'privatekey' => '',
  460. 'publickey' => '',
  461. 'partialkey' => serialize(array(
  462. 'primes' => $primes,
  463. 'coefficients' => $coefficients,
  464. 'lcm' => $lcm,
  465. 'exponents' => $exponents
  466. ))
  467. );
  468. }
  469. }
  470. if ($i == $num_primes) {
  471. list($min, $temp) = $absoluteMin->divide($n);
  472. if (!$temp->equals(self::$zero)) {
  473. $min = $min->add(self::$one); // ie. ceil()
  474. }
  475. $primes[$i] = BigInteger::randomPrime($min, $finalMax, $timeout);
  476. } else {
  477. $primes[$i] = BigInteger::randomPrime($min, $max, $timeout);
  478. }
  479. if ($primes[$i] === false) { // if we've reached the timeout
  480. if (count($primes) > 1) {
  481. $partialkey = '';
  482. } else {
  483. array_pop($primes);
  484. $partialkey = serialize(array(
  485. 'primes' => $primes,
  486. 'coefficients' => $coefficients,
  487. 'lcm' => $lcm,
  488. 'exponents' => $exponents
  489. ));
  490. }
  491. return array(
  492. 'privatekey' => false,
  493. 'publickey' => false,
  494. 'partialkey' => $partialkey
  495. );
  496. }
  497. // the first coefficient is calculated differently from the rest
  498. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  499. if ($i > 2) {
  500. $coefficients[$i] = $n->modInverse($primes[$i]);
  501. }
  502. $n = $n->multiply($primes[$i]);
  503. $temp = $primes[$i]->subtract(self::$one);
  504. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  505. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  506. $lcm['top'] = $lcm['top']->multiply($temp);
  507. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  508. $exponents[$i] = $e->modInverse($temp);
  509. }
  510. list($temp) = $lcm['top']->divide($lcm['bottom']);
  511. $gcd = $temp->gcd($e);
  512. $i0 = 1;
  513. } while (!$gcd->equals(self::$one));
  514. $d = $e->modInverse($temp);
  515. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  516. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  517. // RSAPrivateKey ::= SEQUENCE {
  518. // version Version,
  519. // modulus INTEGER, -- n
  520. // publicExponent INTEGER, -- e
  521. // privateExponent INTEGER, -- d
  522. // prime1 INTEGER, -- p
  523. // prime2 INTEGER, -- q
  524. // exponent1 INTEGER, -- d mod (p-1)
  525. // exponent2 INTEGER, -- d mod (q-1)
  526. // coefficient INTEGER, -- (inverse of q) mod p
  527. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  528. // }
  529. $privatekey = new RSA();
  530. $privatekey->modulus = $n;
  531. $privatekey->k = $bits >> 3;
  532. $privatekey->publicExponent = $e;
  533. $privatekey->exponent = $d;
  534. $privatekey->privateExponent = $e;
  535. $privatekey->primes = $primes;
  536. $privatekey->exponents = $exponents;
  537. $privatekey->coefficients = $coefficients;
  538. $publickey = new RSA();
  539. $publickey->modulus = $n;
  540. $publickey->k = $bits >> 3;
  541. $publickey->exponent = $e;
  542. return array(
  543. 'privatekey' => $privatekey,
  544. 'publickey' => $publickey,
  545. 'partialkey' => false
  546. );
  547. }
  548. /**
  549. * Add a fileformat plugin
  550. *
  551. * The plugin needs to either already be loaded or be auto-loadable.
  552. * Loading a plugin whose shortname overwrite an existing shortname will overwrite the old plugin.
  553. *
  554. * @see self::load()
  555. * @param string $fullname
  556. * @access public
  557. * @return bool
  558. */
  559. static function addFileFormat($fullname)
  560. {
  561. self::_initialize_static_variables();
  562. if (class_exists($fullname)) {
  563. $meta = new \ReflectionClass($path);
  564. $shortname = $meta->getShortName();
  565. self::$fileFormats[strtolower($shortname)] = $fullname;
  566. self::$origFileFormats[] = $shortname;
  567. }
  568. }
  569. /**
  570. * Returns a list of supported formats.
  571. *
  572. * @access public
  573. * @return array
  574. */
  575. static function getSupportedFormats()
  576. {
  577. self::_initialize_static_variables();
  578. return self::$origFileFormats;
  579. }
  580. /**
  581. * Loads a public or private key
  582. *
  583. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  584. *
  585. * @access public
  586. * @param string $key
  587. * @param int $type optional
  588. */
  589. function load($key, $type = false)
  590. {
  591. if ($key instanceof RSA) {
  592. $this->privateKeyFormat = $key->privateKeyFormat;
  593. $this->publicKeyFormat = $key->publicKeyFormat;
  594. $this->k = $key->k;
  595. $this->hLen = $key->hLen;
  596. $this->sLen = $key->sLen;
  597. $this->mgfHLen = $key->mgfHLen;
  598. $this->password = $key->password;
  599. if (is_object($key->hash)) {
  600. $this->hash = new Hash($key->hash->getHash());
  601. }
  602. if (is_object($key->mgfHash)) {
  603. $this->mgfHash = new Hash($key->mgfHash->getHash());
  604. }
  605. if (is_object($key->modulus)) {
  606. $this->modulus = clone $key->modulus;
  607. }
  608. if (is_object($key->exponent)) {
  609. $this->exponent = clone $key->exponent;
  610. }
  611. if (is_object($key->publicExponent)) {
  612. $this->publicExponent = clone $key->publicExponent;
  613. }
  614. $this->primes = array();
  615. $this->exponents = array();
  616. $this->coefficients = array();
  617. foreach ($this->primes as $prime) {
  618. $this->primes[] = clone $prime;
  619. }
  620. foreach ($this->exponents as $exponent) {
  621. $this->exponents[] = clone $exponent;
  622. }
  623. foreach ($this->coefficients as $coefficient) {
  624. $this->coefficients[] = clone $coefficient;
  625. }
  626. return true;
  627. }
  628. $components = false;
  629. if ($type === false) {
  630. foreach (self::$fileFormats as $format) {
  631. try {
  632. $components = $format::load($key, $this->password);
  633. } catch (\Exception $e) {
  634. $components = false;
  635. }
  636. if ($components !== false) {
  637. break;
  638. }
  639. }
  640. } else {
  641. $format = strtolower($type);
  642. if (isset(self::$fileFormats[$format])) {
  643. $format = self::$fileFormats[$format];
  644. try {
  645. $components = $format::load($key, $this->password);
  646. } catch (\Exception $e) {
  647. $components = false;
  648. }
  649. }
  650. }
  651. if ($components === false) {
  652. $this->format = false;
  653. return false;
  654. }
  655. $this->format = $format;
  656. $this->modulus = $components['modulus'];
  657. $this->k = strlen($this->modulus->toBytes());
  658. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  659. if (isset($components['primes'])) {
  660. $this->primes = $components['primes'];
  661. $this->exponents = $components['exponents'];
  662. $this->coefficients = $components['coefficients'];
  663. $this->publicExponent = $components['publicExponent'];
  664. } else {
  665. $this->primes = array();
  666. $this->exponents = array();
  667. $this->coefficients = array();
  668. $this->publicExponent = false;
  669. }
  670. if ($components['isPublicKey']) {
  671. $this->setPublicKey();
  672. }
  673. return true;
  674. }
  675. /**
  676. * Returns the format of the loaded key.
  677. *
  678. * If the key that was loaded wasn't in a valid or if the key was auto-generated
  679. * with RSA::createKey() then this will return false.
  680. *
  681. * @see self::load()
  682. * @access public
  683. * @return mixed
  684. */
  685. function getLoadedFormat()
  686. {
  687. if ($this->format === false) {
  688. return false;
  689. }
  690. $meta = new \ReflectionClass($this->format);
  691. return $meta->getShortName();
  692. }
  693. /**
  694. * Returns the private key
  695. *
  696. * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  697. *
  698. * @see self::getPublicKey()
  699. * @access public
  700. * @param string $type optional
  701. * @return mixed
  702. */
  703. function getPrivateKey($type = 'PKCS1')
  704. {
  705. $type = strtolower($type);
  706. if (!isset(self::$fileFormats[$type])) {
  707. return false;
  708. }
  709. $type = self::$fileFormats[$type];
  710. if (!method_exists($type, 'savePrivateKey')) {
  711. return false;
  712. }
  713. if (empty($this->primes)) {
  714. return false;
  715. }
  716. $oldFormat = $this->privateKeyFormat;
  717. $this->privateKeyFormat = $type;
  718. $temp = $type::savePrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients, $this->password);
  719. $this->privateKeyFormat = $oldFormat;
  720. return $temp;
  721. }
  722. /**
  723. * Returns the key size
  724. *
  725. * More specifically, this returns the size of the modulo in bits.
  726. *
  727. * @access public
  728. * @return int
  729. */
  730. function getSize()
  731. {
  732. return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
  733. }
  734. /**
  735. * Sets the password
  736. *
  737. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  738. * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  739. *
  740. * @see self::createKey()
  741. * @see self::load()
  742. * @access public
  743. * @param string $password
  744. */
  745. function setPassword($password = false)
  746. {
  747. $this->password = $password;
  748. }
  749. /**
  750. * Defines the public key
  751. *
  752. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  753. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  754. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  755. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  756. * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used
  757. * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being
  758. * public.
  759. *
  760. * Do note that when a new key is loaded the index will be cleared.
  761. *
  762. * Returns true on success, false on failure
  763. *
  764. * @see self::getPublicKey()
  765. * @access public
  766. * @param string $key optional
  767. * @param int $type optional
  768. * @return bool
  769. */
  770. function setPublicKey($key = false, $type = false)
  771. {
  772. // if a public key has already been loaded return false
  773. if (!empty($this->publicExponent)) {
  774. return false;
  775. }
  776. if ($key === false && !empty($this->modulus)) {
  777. $this->publicExponent = $this->exponent;
  778. return true;
  779. }
  780. $components = false;
  781. if ($type === false) {
  782. foreach (self::$fileFormats as $format) {
  783. if (!method_exists($format, 'savePublicKey')) {
  784. continue;
  785. }
  786. try {
  787. $components = $format::load($key, $this->password);
  788. } catch (\Exception $e) {
  789. $components = false;
  790. }
  791. if ($components !== false) {
  792. break;
  793. }
  794. }
  795. } else {
  796. $format = strtolower($type);
  797. if (isset(self::$fileFormats[$format])) {
  798. $format = self::$fileFormats[$format];
  799. try {
  800. $components = $format::load($key, $this->password);
  801. } catch (\Exception $e) {
  802. $components = false;
  803. }
  804. }
  805. }
  806. if ($components === false) {
  807. $this->format = false;
  808. return false;
  809. }
  810. $this->format = $format;
  811. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  812. $this->modulus = $components['modulus'];
  813. $this->exponent = $this->publicExponent = $components['publicExponent'];
  814. return true;
  815. }
  816. $this->publicExponent = $components['publicExponent'];
  817. return true;
  818. }
  819. /**
  820. * Defines the private key
  821. *
  822. * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force
  823. * phpseclib to treat the key as a private key. This function will do that.
  824. *
  825. * Do note that when a new key is loaded the index will be cleared.
  826. *
  827. * Returns true on success, false on failure
  828. *
  829. * @see self::getPublicKey()
  830. * @access public
  831. * @param string $key optional
  832. * @param int $type optional
  833. * @return bool
  834. */
  835. function setPrivateKey($key = false, $type = false)
  836. {
  837. if ($key === false && !empty($this->publicExponent)) {
  838. $this->publicExponent = false;
  839. return true;
  840. }
  841. $rsa = new RSA();
  842. if (!$rsa->load($key, $type)) {
  843. return false;
  844. }
  845. $rsa->publicExponent = false;
  846. // don't overwrite the old key if the new key is invalid
  847. $this->load($rsa);
  848. return true;
  849. }
  850. /**
  851. * Returns the public key
  852. *
  853. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  854. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  855. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  856. *
  857. * @see self::getPrivateKey()
  858. * @access public
  859. * @param string $type optional
  860. * @return mixed
  861. */
  862. function getPublicKey($type = 'PKCS8')
  863. {
  864. $type = strtolower($type);
  865. if (!isset(self::$fileFormats[$type])) {
  866. return false;
  867. }
  868. $type = self::$fileFormats[$type];
  869. if (!method_exists($type, 'savePublicKey')) {
  870. return false;
  871. }
  872. if (empty($this->modulus) || empty($this->publicExponent)) {
  873. return false;
  874. }
  875. $oldFormat = $this->publicKeyFormat;
  876. $this->publicKeyFormat = $type;
  877. $temp = $type::savePublicKey($this->modulus, $this->publicExponent);
  878. $this->publicKeyFormat = $oldFormat;
  879. return $temp;
  880. }
  881. /**
  882. * Returns the public key's fingerprint
  883. *
  884. * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
  885. * no public key currently loaded, false is returned.
  886. * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
  887. *
  888. * @access public
  889. * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
  890. * for invalid values.
  891. * @return mixed
  892. */
  893. function getPublicKeyFingerprint($algorithm = 'md5')
  894. {
  895. if (empty($this->modulus) || empty($this->publicExponent)) {
  896. return false;
  897. }
  898. $modulus = $this->modulus->toBytes(true);
  899. $publicExponent = $this->publicExponent->toBytes(true);
  900. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  901. switch ($algorithm) {
  902. case 'sha256':
  903. $hash = new Hash('sha256');
  904. $base = Base64::encode($hash->hash($RSAPublicKey));
  905. return substr($base, 0, strlen($base) - 1);
  906. case 'md5':
  907. return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1);
  908. default:
  909. return false;
  910. }
  911. }
  912. /**
  913. * Returns a minimalistic private key
  914. *
  915. * Returns the private key without the prime number constituants. Structurally identical to a public key that
  916. * hasn't been set as the public key
  917. *
  918. * @see self::getPrivateKey()
  919. * @access private
  920. * @param string $type optional
  921. * @return mixed
  922. */
  923. function _getPrivatePublicKey($type = 'PKCS8')
  924. {
  925. $type = strtolower($type);
  926. if (!isset(self::$fileFormats[$type])) {
  927. return false;
  928. }
  929. $type = self::$fileFormats[$type];
  930. if (!method_exists($type, 'savePublicKey')) {
  931. return false;
  932. }
  933. if (empty($this->modulus) || empty($this->exponent)) {
  934. return false;
  935. }
  936. $oldFormat = $this->publicKeyFormat;
  937. $this->publicKeyFormat = $type;
  938. $temp = $type::savePublicKey($this->modulus, $this->exponent);
  939. $this->publicKeyFormat = $oldFormat;
  940. return $temp;
  941. }
  942. /**
  943. * __toString() magic method
  944. *
  945. * @access public
  946. * @return string
  947. */
  948. function __toString()
  949. {
  950. $key = $this->getPrivateKey($this->privateKeyFormat);
  951. if (is_string($key)) {
  952. return $key;
  953. }
  954. $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
  955. return is_string($key) ? $key : '';
  956. }
  957. /**
  958. * __clone() magic method
  959. *
  960. * @access public
  961. * @return \phpseclib\Crypt\RSA
  962. */
  963. function __clone()
  964. {
  965. $key = new RSA();
  966. $key->load($this);
  967. return $key;
  968. }
  969. /**
  970. * Generates the smallest and largest numbers requiring $bits bits
  971. *
  972. * @access private
  973. * @param int $bits
  974. * @return array
  975. */
  976. static function _generateMinMax($bits)
  977. {
  978. $bytes = $bits >> 3;
  979. $min = str_repeat(chr(0), $bytes);
  980. $max = str_repeat(chr(0xFF), $bytes);
  981. $msb = $bits & 7;
  982. if ($msb) {
  983. $min = chr(1 << ($msb - 1)) . $min;
  984. $max = chr((1 << $msb) - 1) . $max;
  985. } else {
  986. $min[0] = chr(0x80);
  987. }
  988. return array(
  989. 'min' => new BigInteger($min, 256),
  990. 'max' => new BigInteger($max, 256)
  991. );
  992. }
  993. /**
  994. * DER-decode the length
  995. *
  996. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  997. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  998. *
  999. * @access private
  1000. * @param string $string
  1001. * @return int
  1002. */
  1003. function _decodeLength(&$string)
  1004. {
  1005. $length = ord($this->_string_shift($string));
  1006. if ($length & 0x80) { // definite length, long form
  1007. $length&= 0x7F;
  1008. $temp = $this->_string_shift($string, $length);
  1009. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1010. }
  1011. return $length;
  1012. }
  1013. /**
  1014. * DER-encode the length
  1015. *
  1016. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1017. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1018. *
  1019. * @access private
  1020. * @param int $length
  1021. * @return string
  1022. */
  1023. function _encodeLength($length)
  1024. {
  1025. if ($length <= 0x7F) {
  1026. return chr($length);
  1027. }
  1028. $temp = ltrim(pack('N', $length), chr(0));
  1029. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1030. }
  1031. /**
  1032. * String Shift
  1033. *
  1034. * Inspired by array_shift
  1035. *
  1036. * @param string $string
  1037. * @param int $index
  1038. * @return string
  1039. * @access private
  1040. */
  1041. function _string_shift(&$string, $index = 1)
  1042. {
  1043. $substr = substr($string, 0, $index);
  1044. $string = substr($string, $index);
  1045. return $substr;
  1046. }
  1047. /**
  1048. * Determines the private key format
  1049. *
  1050. * @see self::createKey()
  1051. * @access public
  1052. * @param int $format
  1053. */
  1054. function setPrivateKeyFormat($format)
  1055. {
  1056. $this->privateKeyFormat = $format;
  1057. }
  1058. /**
  1059. * Determines the public key format
  1060. *
  1061. * @see self::createKey()
  1062. * @access public
  1063. * @param int $format
  1064. */
  1065. function setPublicKeyFormat($format)
  1066. {
  1067. $this->publicKeyFormat = $format;
  1068. }
  1069. /**
  1070. * Determines which hashing function should be used
  1071. *
  1072. * Used with signature production / verification and (if the encryption mode is self::PADDING_OAEP) encryption and
  1073. * decryption. If $hash isn't supported, sha256 is used.
  1074. *
  1075. * @access public
  1076. * @param string $hash
  1077. */
  1078. function setHash($hash)
  1079. {
  1080. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1081. switch ($hash) {
  1082. case 'md2':
  1083. case 'md5':
  1084. case 'sha1':
  1085. case 'sha256':
  1086. case 'sha384':
  1087. case 'sha512':
  1088. case 'sha224':
  1089. case 'sha512/224':
  1090. case 'sha512/256':
  1091. $this->hash = new Hash($hash);
  1092. $this->hashName = $hash;
  1093. break;
  1094. default:
  1095. $this->hash = new Hash('sha256');
  1096. $this->hashName = 'sha256';
  1097. }
  1098. $this->hLen = $this->hash->getLength();
  1099. }
  1100. /**
  1101. * Determines which hashing function should be used for the mask generation function
  1102. *
  1103. * The mask generation function is used by self::PADDING_OAEP and self::PADDING_PSS and although it's
  1104. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1105. *
  1106. * @access public
  1107. * @param string $hash
  1108. */
  1109. function setMGFHash($hash)
  1110. {
  1111. // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1112. switch ($hash) {
  1113. case 'md2':
  1114. case 'md5':
  1115. case 'sha1':
  1116. case 'sha256':
  1117. case 'sha384':
  1118. case 'sha512':
  1119. case 'sha224':
  1120. case 'sha512/224':
  1121. case 'sha512/256':
  1122. $this->mgfHash = new Hash($hash);
  1123. break;
  1124. default:
  1125. $this->mgfHash = new Hash('sha256');
  1126. }
  1127. $this->mgfHLen = $this->mgfHash->getLength();
  1128. }
  1129. /**
  1130. * Determines the salt length
  1131. *
  1132. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1133. *
  1134. * Typical salt lengths in octets are hLen (the length of the output
  1135. * of the hash function Hash) and 0.
  1136. *
  1137. * @access public
  1138. * @param int $format
  1139. */
  1140. function setSaltLength($sLen)
  1141. {
  1142. $this->sLen = $sLen;
  1143. }
  1144. /**
  1145. * Integer-to-Octet-String primitive
  1146. *
  1147. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1148. *
  1149. * @access private
  1150. * @param bool|\phpseclib\Math\BigInteger $x
  1151. * @param int $xLen
  1152. * @return bool|string
  1153. */
  1154. function _i2osp($x, $xLen)
  1155. {
  1156. if ($x === false) {
  1157. return false;
  1158. }
  1159. $x = $x->toBytes();
  1160. if (strlen($x) > $xLen) {
  1161. return false;
  1162. }
  1163. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1164. }
  1165. /**
  1166. * Octet-String-to-Integer primitive
  1167. *
  1168. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1169. *
  1170. * @access private
  1171. * @param string $x
  1172. * @return \phpseclib\Math\BigInteger
  1173. */
  1174. function _os2ip($x)
  1175. {
  1176. return new BigInteger($x, 256);
  1177. }
  1178. /**
  1179. * Exponentiate with or without Chinese Remainder Theorem
  1180. *
  1181. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1182. *
  1183. * @access private
  1184. * @param \phpseclib\Math\BigInteger $x
  1185. * @return \phpseclib\Math\BigInteger
  1186. */
  1187. function _exponentiate($x)
  1188. {
  1189. switch (true) {
  1190. case empty($this->primes):
  1191. case $this->primes[1]->equals(self::$zero):
  1192. case empty($this->coefficients):
  1193. case $this->coefficients[2]->equals(self::$zero):
  1194. case empty($this->exponents):
  1195. case $this->exponents[1]->equals(self::$zero):
  1196. return $x->modPow($this->exponent, $this->modulus);
  1197. }
  1198. $num_primes = count($this->primes);
  1199. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1200. $m_i = array(
  1201. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1202. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1203. );
  1204. $h = $m_i[1]->subtract($m_i[2]);
  1205. $h = $h->multiply($this->coefficients[2]);
  1206. list(, $h) = $h->divide($this->primes[1]);
  1207. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1208. $r = $this->primes[1];
  1209. for ($i = 3; $i <= $num_primes; $i++) {
  1210. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1211. $r = $r->multiply($this->primes[$i - 1]);
  1212. $h = $m_i->subtract($m);
  1213. $h = $h->multiply($this->coefficients[$i]);
  1214. list(, $h) = $h->divide($this->primes[$i]);
  1215. $m = $m->add($r->multiply($h));
  1216. }
  1217. } else {
  1218. $smallest = $this->primes[1];
  1219. for ($i = 2; $i <= $num_primes; $i++) {
  1220. if ($smallest->compare($this->primes[$i]) > 0) {
  1221. $smallest = $this->primes[$i];
  1222. }
  1223. }
  1224. $r = BigInteger::random(self::$one, $smallest->subtract(self::$one));
  1225. $m_i = array(
  1226. 1 => $this->_blind($x, $r, 1),
  1227. 2 => $this->_blind($x, $r, 2)
  1228. );
  1229. $h = $m_i[1]->subtract($m_i[2]);
  1230. $h = $h->multiply($this->coefficients[2]);
  1231. list(, $h) = $h->divide($this->primes[1]);
  1232. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1233. $r = $this->primes[1];
  1234. for ($i = 3; $i <= $num_primes; $i++) {
  1235. $m_i = $this->_blind($x, $r, $i);
  1236. $r = $r->multiply($this->primes[$i - 1]);
  1237. $h = $m_i->subtract($m);
  1238. $h = $h->multiply($this->coefficients[$i]);
  1239. list(, $h) = $h->divide($this->primes[$i]);
  1240. $m = $m->add($r->multiply($h));
  1241. }
  1242. }
  1243. return $m;
  1244. }
  1245. /**
  1246. * Performs RSA Blinding
  1247. *
  1248. * Protects against timing attacks by employing RSA Blinding.
  1249. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1250. *
  1251. * @access private
  1252. * @param \phpseclib\Math\BigInteger $x
  1253. * @param \phpseclib\Math\BigInteger $r
  1254. * @param int $i
  1255. * @return \phpseclib\Math\BigInteger
  1256. */
  1257. function _blind($x, $r, $i)
  1258. {
  1259. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1260. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1261. $r = $r->modInverse($this->primes[$i]);
  1262. $x = $x->multiply($r);
  1263. list(, $x) = $x->divide($this->primes[$i]);
  1264. return $x;
  1265. }
  1266. /**
  1267. * Performs blinded RSA equality testing
  1268. *
  1269. * Protects against a particular type of timing attack described.
  1270. *
  1271. * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
  1272. *
  1273. * Thanks for the heads up singpolyma!
  1274. *
  1275. * @access private
  1276. * @param string $x
  1277. * @param string $y
  1278. * @return bool
  1279. */
  1280. function _equals($x, $y)
  1281. {
  1282. if (strlen($x) != strlen($y)) {
  1283. return false;
  1284. }
  1285. $result = 0;
  1286. for ($i = 0; $i < strlen($x); $i++) {
  1287. $result |= ord($x[$i]) ^ ord($y[$i]);
  1288. }
  1289. return $result == 0;
  1290. }
  1291. /**
  1292. * RSAEP
  1293. *
  1294. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1295. *
  1296. * @access private
  1297. * @param \phpseclib\Math\BigInteger $m
  1298. * @return bool|\phpseclib\Math\BigInteger
  1299. */
  1300. function _rsaep($m)
  1301. {
  1302. if ($m->compare(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
  1303. return false;
  1304. }
  1305. return $this->_exponentiate($m);
  1306. }
  1307. /**
  1308. * RSADP
  1309. *
  1310. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  1311. *
  1312. * @access private
  1313. * @param \phpseclib\Math\BigInteger $c
  1314. * @return bool|\phpseclib\Math\BigInteger
  1315. */
  1316. function _rsadp($c)
  1317. {
  1318. if ($c->compare(self::$zero) < 0 || $c->compare($this->modulus) > 0) {
  1319. return false;
  1320. }
  1321. return $this->_exponentiate($c);
  1322. }
  1323. /**
  1324. * RSASP1
  1325. *
  1326. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  1327. *
  1328. * @access private
  1329. * @param \phpseclib\Math\BigInteger $m
  1330. * @return bool|\phpseclib\Math\BigInteger
  1331. */
  1332. function _rsasp1($m)
  1333. {
  1334. if ($m->compare(self::$zero) < 0 || $m->compare($this->modulus) > 0) {
  1335. return false;
  1336. }
  1337. return $this->_exponentiate($m);
  1338. }
  1339. /**
  1340. * RSAVP1
  1341. *
  1342. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  1343. *
  1344. * @access private
  1345. * @param \phpseclib\Math\BigInteger $s
  1346. * @return bool|\phpseclib\Math\BigInteger
  1347. */
  1348. function _rsavp1($s)
  1349. {
  1350. if ($s->compare(self::$zero) < 0 || $s->compare($this->modulus) > 0) {
  1351. return false;
  1352. }
  1353. return $this->_exponentiate($s);
  1354. }
  1355. /**
  1356. * MGF1
  1357. *
  1358. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  1359. *
  1360. * @access private
  1361. * @param string $mgfSeed
  1362. * @param int $mgfLen
  1363. * @return string
  1364. */
  1365. function _mgf1($mgfSeed, $maskLen)
  1366. {
  1367. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  1368. $t = '';
  1369. $count = ceil($maskLen / $this->mgfHLen);
  1370. for ($i = 0; $i < $count; $i++) {
  1371. $c = pack('N', $i);
  1372. $t.= $this->mgfHash->hash($mgfSeed . $c);
  1373. }
  1374. return substr($t, 0, $maskLen);
  1375. }
  1376. /**
  1377. * RSAES-OAEP-ENCRYPT
  1378. *
  1379. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  1380. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  1381. *
  1382. * @access private
  1383. * @param string $m
  1384. * @param string $l
  1385. * @throws \OutOfBoundsException if strlen($m) > $this->k - 2 * $this->hLen - 2
  1386. * @return string
  1387. */
  1388. function _rsaes_oaep_encrypt($m, $l = '')
  1389. {
  1390. $mLen = strlen($m);
  1391. // Length checking
  1392. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1393. // be output.
  1394. if ($mLen > $this->k - 2 * $this->hLen - 2) {
  1395. throw new \OutOfBoundsException('Message too long');
  1396. }
  1397. // EME-OAEP encoding
  1398. $lHash = $this->hash->hash($l);
  1399. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  1400. $db = $lHash . $ps . chr(1) . $m;
  1401. $seed = Random::string($this->hLen);
  1402. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1403. $maskedDB = $db ^ $dbMask;
  1404. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1405. $maskedSeed = $seed ^ $seedMask;
  1406. $em = chr(0) . $maskedSeed . $maskedDB;
  1407. // RSA encryption
  1408. $m = $this->_os2ip($em);
  1409. $c = $this->_rsaep($m);
  1410. $c = $this->_i2osp($c, $this->k);
  1411. // Output the ciphertext C
  1412. return $c;
  1413. }
  1414. /**
  1415. * RSAES-OAEP-DECRYPT
  1416. *
  1417. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  1418. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  1419. *
  1420. * Note. Care must be taken to ensure that an opponent cannot
  1421. * distinguish the different error conditions in Step 3.g, whether by
  1422. * error message or timing, or, more generally, learn partial
  1423. * information about the encoded message EM. Otherwise an opponent may
  1424. * be able to obtain useful information about the decryption of the
  1425. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  1426. * observed by Manger [36].
  1427. *
  1428. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  1429. *
  1430. * Both the encryption and the decryption operations of RSAES-OAEP take
  1431. * the value of a label L as input. In this version of PKCS #1, L is
  1432. * the empty string; other uses of the label are outside the scope of
  1433. * this document.
  1434. *
  1435. * @access private
  1436. * @param string $c
  1437. * @param string $l
  1438. * @return bool|string
  1439. */
  1440. function _rsaes_oaep_decrypt($c, $l = '')
  1441. {
  1442. // Length checking
  1443. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1444. // be output.
  1445. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  1446. return false;
  1447. }
  1448. // RSA decryption
  1449. $c = $this->_os2ip($c);
  1450. $m = $this->_rsadp($c);
  1451. $em = $this->_i2osp($m, $this->k);
  1452. if ($em === false) {
  1453. return false;
  1454. }
  1455. // EME-OAEP decoding
  1456. $lHash = $this->hash->hash($l);
  1457. $y = ord($em[0]);
  1458. $maskedSeed = substr($em, 1, $this->hLen);
  1459. $maskedDB = substr($em, $this->hLen + 1);
  1460. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1461. $seed = $maskedSeed ^ $seedMask;
  1462. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1463. $db = $maskedDB ^ $dbMask;
  1464. $lHash2 = substr($db, 0, $this->hLen);
  1465. $m = substr($db, $this->hLen);
  1466. if ($lHash != $lHash2) {
  1467. return false;
  1468. }
  1469. $m = ltrim($m, chr(0));
  1470. if (ord($m[0]) != 1) {
  1471. return false;
  1472. }
  1473. // Output the message M
  1474. return substr($m, 1);
  1475. }
  1476. /**
  1477. * Raw Encryption / Decryption
  1478. *
  1479. * Doesn't use padding and is not recommended.
  1480. *
  1481. * @access private
  1482. * @param string $m
  1483. * @return bool|string
  1484. * @throws \OutOfBoundsException if strlen($m) > $this->k
  1485. */
  1486. function _raw_encrypt($m)
  1487. {
  1488. if (strlen($m) > $this->k) {
  1489. throw new \OutOfBoundsException('Message too long');
  1490. }
  1491. $temp = $this->_os2ip($m);
  1492. $temp = $this->_rsaep($temp);
  1493. return $this->_i2osp($temp, $this->k);
  1494. }
  1495. /**
  1496. * RSAES-PKCS1-V1_5-ENCRYPT
  1497. *
  1498. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  1499. *
  1500. * @access private
  1501. * @param string $m
  1502. * @param bool $pkcs15_compat optional
  1503. * @throws \OutOfBoundsException if strlen($m) > $this->k - 11
  1504. * @return bool|string
  1505. */
  1506. function _rsaes_pkcs1_v1_5_encrypt($m, $pkcs15_compat = false)
  1507. {
  1508. $mLen = strlen($m);
  1509. // Length checking
  1510. if ($mLen > $this->k - 11) {
  1511. throw new \OutOfBoundsException('Message too long');
  1512. }
  1513. // EME-PKCS1-v1_5 encoding
  1514. $psLen = $this->k - $mLen - 3;
  1515. $ps = '';
  1516. while (strlen($ps) != $psLen) {
  1517. $temp = Random::string($psLen - strlen($ps));
  1518. $temp = str_replace("\x00", '', $temp);
  1519. $ps.= $temp;
  1520. }
  1521. $type = 2;
  1522. // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  1523. if ($pkcs15_compat && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) {
  1524. $type = 1;
  1525. // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  1526. $ps = str_repeat("\xFF", $psLen);
  1527. }
  1528. $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  1529. // RSA encryption
  1530. $m = $this->_os2ip($em);
  1531. $c = $this->_rsaep($m);
  1532. $c = $this->_i2osp($c, $this->k);
  1533. // Output the ciphertext C
  1534. return $c;
  1535. }
  1536. /**
  1537. * RSAES-PKCS1-V1_5-DECRYPT
  1538. *
  1539. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  1540. *
  1541. * For compatibility purposes, this function departs slightly from the description given in RFC3447.
  1542. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  1543. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  1544. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  1545. * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
  1546. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  1547. *
  1548. * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt
  1549. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  1550. * not private key encrypted ciphertext's.
  1551. *
  1552. * @access private
  1553. * @param string $c
  1554. * @return bool|string
  1555. */
  1556. function _rsaes_pkcs1_v1_5_decrypt($c)
  1557. {
  1558. // Length checking
  1559. if (strlen($c) != $this->k) { // or if k < 11
  1560. return false;
  1561. }
  1562. // RSA decryption
  1563. $c = $this->_os2ip($c);
  1564. $m = $this->_rsadp($c);
  1565. $em = $this->_i2osp($m, $this->k);
  1566. if ($em === false) {
  1567. return false;
  1568. }
  1569. // EME-PKCS1-v1_5 decoding
  1570. if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  1571. return false;
  1572. }
  1573. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  1574. $m = substr($em, strlen($ps) + 3);
  1575. if (strlen($ps) < 8) {
  1576. return false;
  1577. }
  1578. // Output M
  1579. return $m;
  1580. }
  1581. /**
  1582. * EMSA-PSS-ENCODE
  1583. *
  1584. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  1585. *
  1586. * @access private
  1587. * @param string $m
  1588. * @throws \RuntimeException on encoding error
  1589. * @param int $emBits
  1590. */
  1591. function _emsa_pss_encode($m, $emBits)
  1592. {
  1593. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1594. // be output.
  1595. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  1596. $sLen = $this->sLen ? $this->sLen : $this->hLen;
  1597. $mHash = $this->hash->hash($m);
  1598. if ($emLen < $this->hLen + $sLen + 2) {
  1599. return false;
  1600. }
  1601. $salt = Random::string($sLen);
  1602. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1603. $h = $this->hash->hash($m2);
  1604. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  1605. $db = $ps . chr(1) . $salt;
  1606. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  1607. $maskedDB = $db ^ $dbMask;
  1608. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  1609. $em = $maskedDB . $h . chr(0xBC);
  1610. return $em;
  1611. }
  1612. /**
  1613. * EMSA-PSS-VERIFY
  1614. *
  1615. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  1616. *
  1617. * @access private
  1618. * @param string $m
  1619. * @param string $em
  1620. * @param int $emBits
  1621. * @return string
  1622. */
  1623. function _emsa_pss_verify($m, $em, $emBits)
  1624. {
  1625. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1626. // be output.
  1627. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  1628. $sLen = $this->sLen ? $this->sLen : $this->hLen;
  1629. $mHash = $this->hash->hash($m);
  1630. if ($emLen < $this->hLen + $sLen + 2) {
  1631. return false;
  1632. }
  1633. if ($em[strlen($em) - 1] != chr(0xBC)) {
  1634. return false;
  1635. }
  1636. $maskedDB = substr($em, 0, -$this->hLen - 1);
  1637. $h = substr($em, -$this->hLen - 1, $this->hLen);
  1638. $temp = chr(0xFF << ($emBits & 7));
  1639. if ((~$maskedDB[0] & $temp) != $temp) {
  1640. return false;
  1641. }
  1642. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  1643. $db = $maskedDB ^ $dbMask;
  1644. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  1645. $temp = $emLen - $this->hLen - $sLen - 2;
  1646. if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  1647. return false;
  1648. }
  1649. $salt = substr($db, $temp + 1); // should be $sLen long
  1650. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1651. $h2 = $this->hash->hash($m2);
  1652. return $this->_equals($h, $h2);
  1653. }
  1654. /**
  1655. * RSASSA-PSS-SIGN
  1656. *
  1657. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  1658. *
  1659. * @access private
  1660. * @param string $m
  1661. * @return bool|string
  1662. */
  1663. function _rsassa_pss_sign($m)
  1664. {
  1665. // EMSA-PSS encoding
  1666. $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  1667. // RSA signature
  1668. $m = $this->_os2ip($em);
  1669. $s = $this->_rsasp1($m);
  1670. $s = $this->_i2osp($s, $this->k);
  1671. // Output the signature S
  1672. return $s;
  1673. }
  1674. /**
  1675. * RSASSA-PSS-VERIFY
  1676. *
  1677. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  1678. *
  1679. * @access private
  1680. * @param string $m
  1681. * @param string $s
  1682. * @return bool|string
  1683. */
  1684. function _rsassa_pss_verify($m, $s)
  1685. {
  1686. // Length checking
  1687. if (strlen($s) != $this->k) {
  1688. return false;
  1689. }
  1690. // RSA verification
  1691. $modBits = 8 * $this->k;
  1692. $s2 = $this->_os2ip($s);
  1693. $m2 = $this->_rsavp1($s2);
  1694. $em = $this->_i2osp($m2, $modBits >> 3);
  1695. if ($em === false) {
  1696. return false;
  1697. }
  1698. // EMSA-PSS verification
  1699. return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  1700. }
  1701. /**
  1702. * EMSA-PKCS1-V1_5-ENCODE
  1703. *
  1704. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  1705. *
  1706. * @access private
  1707. * @param string $m
  1708. * @param int $emLen
  1709. * @throws \LengthException if the intended encoded message length is too short
  1710. * @return string
  1711. */
  1712. function _emsa_pkcs1_v1_5_encode($m, $emLen)
  1713. {
  1714. $h = $this->hash->hash($m);
  1715. // see http://tools.ietf.org/html/rfc3447#page-43
  1716. switch ($this->hashName) {
  1717. case 'md2':
  1718. $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10";
  1719. break;
  1720. case 'md5':
  1721. $t = "\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10";
  1722. break;
  1723. case 'sha1':
  1724. $t = "\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14";
  1725. break;
  1726. case 'sha256':
  1727. $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20";
  1728. break;
  1729. case 'sha384':
  1730. $t = "\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30";
  1731. break;
  1732. case 'sha512':
  1733. $t = "\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40";
  1734. break;
  1735. // from https://www.emc.com/collateral/white-papers/h11300-pkcs-1v2-2-rsa-cryptography-standard-wp.pdf#page=40
  1736. case 'sha224':
  1737. $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c";
  1738. break;
  1739. case 'sha512/224':
  1740. $t = "\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x05\x05\x00\x04\x1c";
  1741. break;
  1742. case 'sha512/256':
  1743. $t = "\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x06\x05\x00\x04\x20";
  1744. }
  1745. $t.= $h;
  1746. $tLen = strlen($t);
  1747. if ($emLen < $tLen + 11) {
  1748. throw new \LengthException('Intended encoded message length too short');
  1749. }
  1750. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  1751. $em = "\0\1$ps\0$t";
  1752. return $em;
  1753. }
  1754. /**
  1755. * RSASSA-PKCS1-V1_5-SIGN
  1756. *
  1757. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  1758. *
  1759. * @access private
  1760. * @param string $m
  1761. * @throws \LengthException if the RSA modulus is too short
  1762. * @return bool|string
  1763. */
  1764. function _rsassa_pkcs1_v1_5_sign($m)
  1765. {
  1766. // EMSA-PKCS1-v1_5 encoding
  1767. // If the encoding operation outputs "intended encoded message length too short," output "RSA modulus
  1768. // too short" and stop.
  1769. try {
  1770. $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  1771. } catch (\LengthException $e) {
  1772. throw new \LengthException('RSA modulus too short');
  1773. }
  1774. // RSA signature
  1775. $m = $this->_os2ip($em);
  1776. $s = $this->_rsasp1($m);
  1777. $s = $this->_i2osp($s, $this->k);
  1778. // Output the signature S
  1779. return $s;
  1780. }
  1781. /**
  1782. * RSASSA-PKCS1-V1_5-VERIFY
  1783. *
  1784. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  1785. *
  1786. * @access private
  1787. * @param string $m
  1788. * @param string $s
  1789. * @throws \LengthException if the RSA modulus is too short
  1790. * @return bool
  1791. */
  1792. function _rsassa_pkcs1_v1_5_verify($m, $s)
  1793. {
  1794. // Length checking
  1795. if (strlen($s) != $this->k) {
  1796. return false;
  1797. }
  1798. // RSA verification
  1799. $s = $this->_os2ip($s);
  1800. $m2 = $this->_rsavp1($s);
  1801. $em = $this->_i2osp($m2, $this->k);
  1802. if ($em === false) {
  1803. return false;
  1804. }
  1805. // EMSA-PKCS1-v1_5 encoding
  1806. // If the encoding operation outputs "intended encoded message length too short," output "RSA modulus
  1807. // too short" and stop.
  1808. try {
  1809. $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  1810. } catch (\LengthException $e) {
  1811. throw new \LengthException('RSA modulus too short');
  1812. }
  1813. // Compare
  1814. return $this->_equals($em, $em2);
  1815. }
  1816. /**
  1817. * RSASSA-PKCS1-V1_5-VERIFY (relaxed matching)
  1818. *
  1819. * Per {@link http://tools.ietf.org/html/rfc3447#page-43 RFC3447#page-43} PKCS1 v1.5
  1820. * specified the use BER encoding rather than DER encoding that PKCS1 v2.0 specified.
  1821. * This means that under rare conditions you can have a perfectly valid v1.5 signature
  1822. * that fails to validate with _rsassa_pkcs1_v1_5_verify(). PKCS1 v2.1 also recommends
  1823. * that if you're going to validate these types of signatures you "should indicate
  1824. * whether the underlying BER encoding is a DER encoding and hence whether the signature
  1825. * is valid with respect to the specification given in [PKCS1 v2.0+]". so if you do
  1826. * $rsa->getLastPadding() and get RSA::PADDING_RELAXED_PKCS1 back instead of
  1827. * RSA::PADDING_PKCS1... that means BER encoding was used.
  1828. *
  1829. * @access private
  1830. * @param string $m
  1831. * @param string $s
  1832. * @return bool
  1833. */
  1834. function _rsassa_pkcs1_v1_5_relaxed_verify($m, $s)
  1835. {
  1836. // Length checking
  1837. if (strlen($s) != $this->k) {
  1838. return false;
  1839. }
  1840. // RSA verification
  1841. $s = $this->_os2ip($s);
  1842. $m2 = $this->_rsavp1($s);
  1843. if ($m2 === false) {
  1844. return false;
  1845. }
  1846. $em = $this->_i2osp($m2, $this->k);
  1847. if ($em === false) {
  1848. return false;
  1849. }
  1850. if ($this->_string_shift($em, 2) != "\0\1") {
  1851. return false;
  1852. }
  1853. $em = ltrim($em, "\xFF");
  1854. if ($this->_string_shift($em) != "\0") {
  1855. return false;
  1856. }
  1857. $asn1 = new ASN1();
  1858. $decoded = $asn1->decodeBER($em);
  1859. if (!is_array($decoded) || empty($decoded[0]) || strlen($em) > $decoded[0]['length']) {
  1860. return false;
  1861. }
  1862. $AlgorithmIdentifier = array(
  1863. 'type' => ASN1::TYPE_SEQUENCE,
  1864. 'children' => array(
  1865. 'algorithm' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER),
  1866. 'parameters' => array(
  1867. 'type' => ASN1::TYPE_ANY,
  1868. 'optional' => true
  1869. )
  1870. )
  1871. );
  1872. $DigestInfo = array(
  1873. 'type' => ASN1::TYPE_SEQUENCE,
  1874. 'children' => array(
  1875. 'digestAlgorithm' => $AlgorithmIdentifier,
  1876. 'digest' => array('type' => ASN1::TYPE_OCTET_STRING)
  1877. )
  1878. );
  1879. $oids = array(
  1880. '1.2.840.113549.2.2' => 'md2',
  1881. '1.2.840.113549.2.4' => 'md4', // from PKCS1 v1.5
  1882. '1.2.840.113549.2.5' => 'md5',
  1883. '1.3.14.3.2.26' => 'sha1',
  1884. '2.16.840.1.101.3.4.2.1' => 'sha256',
  1885. '2.16.840.1.101.3.4.2.2' => 'sha384',
  1886. '2.16.840.1.101.3.4.2.3' => 'sha512',
  1887. // from PKCS1 v2.2
  1888. '2.16.840.1.101.3.4.2.4' => 'sha224',
  1889. '2.16.840.1.101.3.4.2.5' => 'sha512/224',
  1890. '2.16.840.1.101.3.4.2.6' => 'sha512/256',
  1891. );
  1892. $asn1->loadOIDs($oids);
  1893. $decoded = $asn1->asn1map($decoded[0], $DigestInfo);
  1894. if (!isset($decoded) || $decoded === false) {
  1895. return false;
  1896. }
  1897. if (!in_array($decoded['digestAlgorithm']['algorithm'], $oids)) {
  1898. return false;
  1899. }
  1900. $hash = new Hash($decoded['digestAlgorithm']['algorithm']);
  1901. $em = $hash->hash($m);
  1902. $em2 = Base64::decode($decoded['digest']);
  1903. return $this->_equals($em, $em2);
  1904. }
  1905. /**
  1906. * Encryption
  1907. *
  1908. * Both self::PADDING_OAEP and self::PADDING_PKCS1 both place limits on how long $plaintext can be.
  1909. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  1910. * be concatenated together.
  1911. *
  1912. * @see self::decrypt()
  1913. * @access public
  1914. * @param string $plaintext
  1915. * @param int $padding optional
  1916. * @return bool|string
  1917. * @throws \LengthException if the RSA modulus is too short
  1918. */
  1919. function encrypt($plaintext, $padding = self::PADDING_OAEP)
  1920. {
  1921. switch ($padding) {
  1922. case self::PADDING_NONE:
  1923. return $this->_raw_encrypt($plaintext);
  1924. case self::PADDING_PKCS15_COMPAT:
  1925. case self::PADDING_PKCS1:
  1926. return $this->_rsaes_pkcs1_v1_5_encrypt($plaintext, $padding == self::PADDING_PKCS15_COMPAT);
  1927. //case self::PADDING_OAEP:
  1928. default:
  1929. return $this->_rsaes_oaep_encrypt($plaintext);
  1930. }
  1931. }
  1932. /**
  1933. * Decryption
  1934. *
  1935. * @see self::encrypt()
  1936. * @access public
  1937. * @param string $plaintext
  1938. * @param int $padding optional
  1939. * @return bool|string
  1940. */
  1941. function decrypt($ciphertext, $padding = self::PADDING_OAEP)
  1942. {
  1943. switch ($padding) {
  1944. case self::PADDING_NONE:
  1945. return $this->_raw_encrypt($ciphertext);
  1946. case self::PADDING_PKCS1:
  1947. return $this->_rsaes_pkcs1_v1_5_decrypt($ciphertext);
  1948. //case self::PADDING_OAEP:
  1949. default:
  1950. return $this->_rsaes_oaep_decrypt($ciphertext);
  1951. }
  1952. }
  1953. /**
  1954. * Create a signature
  1955. *
  1956. * @see self::verify()
  1957. * @access public
  1958. * @param string $message
  1959. * @param int $padding optional
  1960. * @return string
  1961. */
  1962. function sign($message, $padding = self::PADDING_PSS)
  1963. {
  1964. if (empty($this->modulus) || empty($this->exponent)) {
  1965. return false;
  1966. }
  1967. switch ($padding) {
  1968. case self::PADDING_PKCS1:
  1969. case self::PADDING_RELAXED_PKCS1:
  1970. return $this->_rsassa_pkcs1_v1_5_sign($message);
  1971. //case self::PADDING_PSS:
  1972. default:
  1973. return $this->_rsassa_pss_sign($message);
  1974. }
  1975. }
  1976. /**
  1977. * Verifies a signature
  1978. *
  1979. * @see self::sign()
  1980. * @access public
  1981. * @param string $message
  1982. * @param string $signature
  1983. * @param int $padding optional
  1984. * @return bool
  1985. */
  1986. function verify($message, $signature, $padding = self::PADDING_PSS)
  1987. {
  1988. if (empty($this->modulus) || empty($this->exponent)) {
  1989. return false;
  1990. }
  1991. switch ($padding) {
  1992. case self::PADDING_RELAXED_PKCS1:
  1993. return $this->_rsassa_pkcs1_v1_5_relaxed_verify($message, $signature);
  1994. case self::PADDING_PKCS1:
  1995. return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  1996. //case self::PADDING_PSS:
  1997. default:
  1998. return $this->_rsassa_pss_verify($message, $signature);
  1999. }
  2000. }
  2001. }