AsymmetricKey.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. <?php
  2. /**
  3. * Base Class for all asymmetric key ciphers
  4. *
  5. * PHP version 5
  6. *
  7. * @category Crypt
  8. * @package AsymmetricKey
  9. * @author Jim Wigginton <terrafrost@php.net>
  10. * @copyright 2016 Jim Wigginton
  11. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  12. * @link http://phpseclib.sourceforge.net
  13. */
  14. namespace phpseclib\Crypt\Common;
  15. use phpseclib\Math\BigInteger;
  16. use phpseclib\Crypt\Hash;
  17. use ParagonIE\ConstantTime\Base64;
  18. /**
  19. * Base Class for all stream cipher classes
  20. *
  21. * @package AsymmetricKey
  22. * @author Jim Wigginton <terrafrost@php.net>
  23. */
  24. abstract class AsymmetricKey
  25. {
  26. /**
  27. * Precomputed Zero
  28. *
  29. * @var \phpseclib\Math\BigInteger
  30. * @access private
  31. */
  32. protected static $zero;
  33. /**
  34. * Precomputed One
  35. *
  36. * @var \phpseclib\Math\BigInteger
  37. * @access private
  38. */
  39. protected static $one;
  40. /**
  41. * Engine
  42. *
  43. * This is only used for key generation. Valid values are RSA::ENGINE_INTERNAL and RSA::ENGINE_OPENSSL
  44. *
  45. * @var int
  46. * @access private
  47. */
  48. protected static $engine = NULL;
  49. /**
  50. * OpenSSL configuration file name.
  51. *
  52. * Set to null to use system configuration file.
  53. *
  54. * @see self::createKey()
  55. * @var mixed
  56. * @access public
  57. */
  58. protected static $configFile;
  59. /**
  60. * Supported plugins (lower case)
  61. *
  62. * @see self::initialize_static_variables()
  63. * @var array
  64. * @access private
  65. */
  66. private static $plugins = [];
  67. /**
  68. * Supported plugins (original case)
  69. *
  70. * @see self::initialize_static_variables()
  71. * @var array
  72. * @access private
  73. */
  74. private static $origPlugins = [];
  75. /**
  76. * Supported signature formats (lower case)
  77. *
  78. * @see self::initialize_static_variables()
  79. * @var array
  80. * @access private
  81. */
  82. private static $signatureFormats = [];
  83. /**
  84. * Supported signature formats (original case)
  85. *
  86. * @see self::initialize_static_variables()
  87. * @var array
  88. * @access private
  89. */
  90. private static $signatureFileFormats = [];
  91. /**
  92. * Password
  93. *
  94. * @var string
  95. * @access private
  96. */
  97. protected $password = false;
  98. /**
  99. * Loaded File Format
  100. *
  101. * @var string
  102. * @access private
  103. */
  104. protected $format = false;
  105. /**
  106. * Private Key Format
  107. *
  108. * @var string
  109. * @access private
  110. */
  111. protected $privateKeyFormat = 'PKCS8';
  112. /**
  113. * Public Key Format
  114. *
  115. * @var string
  116. * @access private
  117. */
  118. protected $publicKeyFormat = 'PKCS8';
  119. /**
  120. * Hash function
  121. *
  122. * @var \phpseclib\Crypt\Hash
  123. * @access private
  124. */
  125. protected $hash;
  126. /**
  127. * HMAC function
  128. *
  129. * @var \phpseclib\Crypt\Hash
  130. * @access private
  131. */
  132. private $hmac;
  133. /**#@+
  134. * @access private
  135. * @see self::__construct()
  136. */
  137. /**
  138. * To use the pure-PHP implementation
  139. */
  140. const ENGINE_INTERNAL = 1;
  141. /**
  142. * To use the OpenSSL library
  143. *
  144. * (if enabled; otherwise, the internal implementation will be used)
  145. */
  146. const ENGINE_OPENSSL = 2;
  147. /**#@-*/
  148. /**
  149. * The constructor
  150. *
  151. * @access public
  152. */
  153. public function __construct()
  154. {
  155. self::initialize_static_variables();
  156. $this->hash = new Hash('sha256');
  157. $this->hmac = new Hash('sha256');
  158. }
  159. /**
  160. * Tests engine validity
  161. *
  162. * @access public
  163. * @param int $val
  164. */
  165. public static function isValidEngine($val)
  166. {
  167. switch ($val) {
  168. case self::ENGINE_OPENSSL:
  169. return extension_loaded('openssl') && file_exists(self::$configFile);
  170. case self::ENGINE_INTERNAL:
  171. return true;
  172. }
  173. return false;
  174. }
  175. /**
  176. * Sets the engine
  177. *
  178. * Only used in RSA::createKey. Valid values are RSA::ENGINE_OPENSSL and RSA::ENGINE_INTERNAL
  179. *
  180. * @access public
  181. * @param int $val
  182. */
  183. public static function setPreferredEngine($val)
  184. {
  185. static::$engine = null;
  186. $candidateEngines = [
  187. $val,
  188. self::ENGINE_OPENSSL
  189. ];
  190. foreach ($candidateEngines as $engine) {
  191. if (static::isValidEngine($engine)) {
  192. static::$engine = $engine;
  193. break;
  194. }
  195. }
  196. if (!isset(static::$engine)) {
  197. static::$engine = self::ENGINE_INTERNAL;
  198. }
  199. }
  200. /**
  201. * Returns the engine
  202. *
  203. * @access public
  204. * @return int
  205. */
  206. public static function getEngine()
  207. {
  208. return self::$engine;
  209. }
  210. /**
  211. * Initialize static variables
  212. *
  213. * @access private
  214. */
  215. protected static function initialize_static_variables()
  216. {
  217. if (!isset(self::$zero)) {
  218. self::$zero= new BigInteger(0);
  219. self::$one = new BigInteger(1);
  220. self::$configFile = __DIR__ . '/../openssl.cnf';
  221. }
  222. self::loadPlugins('Keys');
  223. if (static::ALGORITHM != 'RSA') {
  224. self::loadPlugins('Signature');
  225. }
  226. }
  227. /**
  228. * Load Plugins
  229. *
  230. * @params $format
  231. * @access private
  232. */
  233. private static function loadPlugins($format)
  234. {
  235. if (!isset(self::$plugins[static::ALGORITHM][$format])) {
  236. self::$plugins[static::ALGORITHM][$format] = [];
  237. foreach (glob(__DIR__ . '/../' . static::ALGORITHM . '/' . $format . '/*.php') as $file) {
  238. $name = pathinfo($file, PATHINFO_FILENAME);
  239. $type = 'phpseclib\Crypt\\' . static::ALGORITHM . '\\' . $format . '\\' . $name;
  240. self::$plugins[static::ALGORITHM][$format][strtolower($name)] = $type;
  241. self::$origPlugins[static::ALGORITHM][$format][] = $name;
  242. }
  243. }
  244. }
  245. /**
  246. * Validate Plugin
  247. *
  248. * @access private
  249. * @param string $format
  250. * @param string $type
  251. * @param string $method optional
  252. * @return mixed
  253. */
  254. protected static function validatePlugin($format, $type, $method = NULL)
  255. {
  256. $type = strtolower($type);
  257. if (!isset(self::$plugins[static::ALGORITHM][$format][$type])) {
  258. return false;
  259. }
  260. $type = self::$plugins[static::ALGORITHM][$format][$type];
  261. if (isset($method) && !method_exists($type, $method)) {
  262. return false;
  263. }
  264. return $type;
  265. }
  266. /**
  267. * Load the key
  268. *
  269. * @access private
  270. * @param string $key
  271. * @param string $type
  272. * @return array
  273. */
  274. protected function load($key, $type)
  275. {
  276. $components = false;
  277. if ($type === false) {
  278. foreach (self::$plugins[static::ALGORITHM]['Keys'] as $format) {
  279. try {
  280. $components = $format::load($key, $this->password);
  281. } catch (\Exception $e) {
  282. $components = false;
  283. }
  284. if ($components !== false) {
  285. break;
  286. }
  287. }
  288. } else {
  289. $format = strtolower($type);
  290. if (isset(self::$plugins[static::ALGORITHM]['Keys'][$format])) {
  291. $format = self::$plugins[static::ALGORITHM]['Keys'][$format];
  292. $components = $format::load($key, $this->password);
  293. }
  294. }
  295. if ($components === false) {
  296. $this->format = false;
  297. return false;
  298. }
  299. $this->format = $format;
  300. return $components;
  301. }
  302. /**
  303. * Load the public key
  304. *
  305. * @access private
  306. * @param string $key
  307. * @param string $type
  308. * @return array
  309. */
  310. protected function setPublicKey($key, $type)
  311. {
  312. $components = false;
  313. if ($type === false) {
  314. foreach (self::$plugins[static::ALGORITHM]['Keys'] as $format) {
  315. if (!method_exists($format, 'savePublicKey')) {
  316. continue;
  317. }
  318. try {
  319. $components = $format::load($key, $this->password);
  320. } catch (\Exception $e) {
  321. $components = false;
  322. }
  323. if ($components !== false) {
  324. break;
  325. }
  326. }
  327. } else {
  328. $format = strtolower($type);
  329. if (isset(self::$plugins[static::ALGORITHM]['Keys'][$format])) {
  330. $format = self::$plugins[static::ALGORITHM]['Keys'][$format];
  331. $components = $format::load($key, $this->password);
  332. }
  333. }
  334. if ($components === false) {
  335. $this->format = false;
  336. return false;
  337. }
  338. $this->format = $format;
  339. return $components;
  340. }
  341. /**
  342. * Returns a list of supported formats.
  343. *
  344. * @access public
  345. * @return array
  346. */
  347. public static function getSupportedKeyFormats()
  348. {
  349. self::initialize_static_variables();
  350. return self::$plugins[static::ALGORITHM]['Keys'];
  351. }
  352. /**
  353. * Add a fileformat plugin
  354. *
  355. * The plugin needs to either already be loaded or be auto-loadable.
  356. * Loading a plugin whose shortname overwrite an existing shortname will overwrite the old plugin.
  357. *
  358. * @see self::load()
  359. * @param string $fullname
  360. * @access public
  361. * @return bool
  362. */
  363. public static function addFileFormat($fullname)
  364. {
  365. self::initialize_static_variables();
  366. if (class_exists($fullname)) {
  367. $meta = new \ReflectionClass($path);
  368. $shortname = $meta->getShortName();
  369. self::$plugins[static::ALGORITHM]['Keys'][strtolower($shortname)] = $fullname;
  370. self::$origPlugins[static::ALGORITHM]['Keys'][] = $shortname;
  371. }
  372. }
  373. /**
  374. * Returns the public key's fingerprint
  375. *
  376. * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is
  377. * no public key currently loaded, false is returned.
  378. * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716)
  379. *
  380. * @access public
  381. * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned
  382. * for invalid values.
  383. * @return mixed
  384. */
  385. public function getPublicKeyFingerprint($algorithm = 'md5')
  386. {
  387. $type = self::validatePlugin('Keys', 'OpenSSH', 'getBinaryOutput');
  388. if ($type === false) {
  389. return false;
  390. }
  391. $status = $type::getBinaryOutput();
  392. $type::setBinaryOutput(true);
  393. $key = $this->getPublicKey('OpenSSH');
  394. if ($key === false) {
  395. return false;
  396. }
  397. $type::setBinaryOutput($status);
  398. switch ($algorithm) {
  399. case 'sha256':
  400. $hash = new Hash('sha256');
  401. $base = Base64::encode($hash->hash($key));
  402. return substr($base, 0, strlen($base) - 1);
  403. case 'md5':
  404. return substr(chunk_split(md5($key), 2, ':'), 0, -1);
  405. default:
  406. return false;
  407. }
  408. }
  409. /**
  410. * __toString() magic method
  411. *
  412. * @access public
  413. * @return string
  414. */
  415. public function __toString()
  416. {
  417. try {
  418. $key = $this->getPrivateKey($this->privateKeyFormat);
  419. if (is_string($key)) {
  420. return $key;
  421. }
  422. $key = $this->getPublicKey($this->publicKeyFormat);
  423. return is_string($key) ? $key : '';
  424. } catch (\Exception $e) {
  425. return '';
  426. }
  427. }
  428. /**
  429. * __clone() magic method
  430. *
  431. * @access public
  432. * @return static
  433. */
  434. public function __clone()
  435. {
  436. $key = new static();
  437. $key->load($this);
  438. return $key;
  439. }
  440. /**
  441. * Determines the private key format
  442. *
  443. * @see self::__toString()
  444. * @access public
  445. * @param string $format
  446. */
  447. public function setPrivateKeyFormat($format)
  448. {
  449. $this->privateKeyFormat = $format;
  450. }
  451. /**
  452. * Determines the public key format
  453. *
  454. * @see self::__toString()
  455. * @access public
  456. * @param string $format
  457. */
  458. public function setPublicKeyFormat($format)
  459. {
  460. $this->publicKeyFormat = $format;
  461. }
  462. /**
  463. * Returns the format of the loaded key.
  464. *
  465. * If the key that was loaded wasn't in a valid or if the key was auto-generated
  466. * with RSA::createKey() then this will return false.
  467. *
  468. * @see self::load()
  469. * @access public
  470. * @return mixed
  471. */
  472. public function getLoadedFormat()
  473. {
  474. if ($this->format === false) {
  475. return false;
  476. }
  477. $meta = new \ReflectionClass($this->format);
  478. return $meta->getShortName();
  479. }
  480. /**
  481. * Sets the password
  482. *
  483. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  484. * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  485. *
  486. * @see self::createKey()
  487. * @see self::load()
  488. * @access public
  489. * @param string $password
  490. */
  491. public function setPassword($password = false)
  492. {
  493. $this->password = $password;
  494. }
  495. /**
  496. * Determines which hashing function should be used
  497. *
  498. * @access public
  499. * @param string $hash
  500. */
  501. public function setHash($hash)
  502. {
  503. $this->hash = new Hash($hash);
  504. $this->hmac = new Hash($hash);
  505. }
  506. /**
  507. * Compute the pseudorandom k for signature generation,
  508. * using the process specified for deterministic DSA.
  509. *
  510. * @access public
  511. * @param string $h1
  512. * @return string
  513. */
  514. protected function computek($h1)
  515. {
  516. $v = str_repeat("\1", strlen($h1));
  517. $k = str_repeat("\0", strlen($h1));
  518. $x = $this->int2octets($this->x);
  519. $h1 = $this->bits2octets($h1);
  520. $this->hmac->setKey($k);
  521. $k = $this->hmac->hash($v . "\0" . $x . $h1);
  522. $this->hmac->setKey($k);
  523. $v = $this->hmac->hash($v);
  524. $k = $this->hmac->hash($v . "\1" . $x . $h1);
  525. $this->hmac->setKey($k);
  526. $v = $this->hmac->hash($v);
  527. $qlen = $this->q->getLengthInBytes();
  528. while (true) {
  529. $t = '';
  530. while (strlen($t) < $qlen) {
  531. $v = $this->hmac->hash($v);
  532. $t = $t . $v;
  533. }
  534. $k = $this->bits2int($t);
  535. if (!$k->equals(self::$zero) && $k->compare($this->q) < 0) {
  536. break;
  537. }
  538. $k = $this->hmac->hash($v . "\0");
  539. $this->hmac->setKey($k);
  540. $v = $this->hmac->hash($v);
  541. }
  542. return $k;
  543. }
  544. /**
  545. * Integer to Octet String
  546. *
  547. * @access private
  548. * @param \phpseclib\Math\BigInteger $v
  549. * @return string
  550. */
  551. private function int2octets($v)
  552. {
  553. $out = $v->toBytes();
  554. $rolen = $this->q->getLengthInBytes();
  555. if (strlen($out) < $rolen) {
  556. return str_pad($out, $rolen, "\0", STR_PAD_LEFT);
  557. } else if (strlen($out) > $rolen) {
  558. return substr($out, -$rolen);
  559. } else {
  560. return $out;
  561. }
  562. }
  563. /**
  564. * Bit String to Integer
  565. *
  566. * @access private
  567. * @param string $in
  568. * @return \phpseclib\Math\BigInteger
  569. */
  570. protected function bits2int($in)
  571. {
  572. $v = new BigInteger($in, 256);
  573. $vlen = strlen($in) << 3;
  574. $qlen = $this->q->getLength();
  575. if ($vlen > $qlen) {
  576. return $v->bitwise_rightShift($vlen - $qlen);
  577. }
  578. return $v;
  579. }
  580. /**
  581. * Bit String to Octet String
  582. *
  583. * @access private
  584. * @param string $in
  585. * @return string
  586. */
  587. private function bits2octets($in)
  588. {
  589. $z1 = $this->bits2int($in);
  590. $z2 = $z1->subtract($this->q);
  591. return $z2->compare(self::$zero) < 0 ?
  592. $this->int2octets($z1) :
  593. $this->int2octets($z2);
  594. }
  595. }