Encryptor.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\Encryption;
  8. use Magento\Framework\App\DeploymentConfig;
  9. use Magento\Framework\App\ObjectManager;
  10. use Magento\Framework\Encryption\Adapter\EncryptionAdapterInterface;
  11. use Magento\Framework\Encryption\Helper\Security;
  12. use Magento\Framework\Math\Random;
  13. use Magento\Framework\Encryption\Adapter\SodiumChachaIetf;
  14. use Magento\Framework\Encryption\Adapter\Mcrypt;
  15. /**
  16. * Class Encryptor provides basic logic for hashing strings and encrypting/decrypting misc data
  17. */
  18. class Encryptor implements EncryptorInterface
  19. {
  20. /**
  21. * Key of md5 algorithm
  22. */
  23. const HASH_VERSION_MD5 = 0;
  24. /**
  25. * Key of sha256 algorithm
  26. */
  27. const HASH_VERSION_SHA256 = 1;
  28. /**
  29. * Key of latest used algorithm
  30. */
  31. const HASH_VERSION_LATEST = 1;
  32. /**
  33. * Default length of salt in bytes
  34. */
  35. const DEFAULT_SALT_LENGTH = 32;
  36. /**#@+
  37. * Exploded password hash keys
  38. */
  39. const PASSWORD_HASH = 0;
  40. const PASSWORD_SALT = 1;
  41. const PASSWORD_VERSION = 2;
  42. /**#@-*/
  43. /**
  44. * Array key of encryption key in deployment config
  45. */
  46. const PARAM_CRYPT_KEY = 'crypt/key';
  47. /**#@+
  48. * Cipher versions
  49. */
  50. const CIPHER_BLOWFISH = 0;
  51. const CIPHER_RIJNDAEL_128 = 1;
  52. const CIPHER_RIJNDAEL_256 = 2;
  53. const CIPHER_AEAD_CHACHA20POLY1305 = 3;
  54. const CIPHER_LATEST = 3;
  55. /**#@-*/
  56. /**
  57. * Default hash string delimiter
  58. */
  59. const DELIMITER = ':';
  60. /**
  61. * @var array map of hash versions
  62. */
  63. private $hashVersionMap = [
  64. self::HASH_VERSION_MD5 => 'md5',
  65. self::HASH_VERSION_SHA256 => 'sha256'
  66. ];
  67. /**
  68. * @var array map of password hash
  69. */
  70. private $passwordHashMap = [
  71. self::PASSWORD_HASH => '',
  72. self::PASSWORD_SALT => '',
  73. self::PASSWORD_VERSION => self::HASH_VERSION_LATEST
  74. ];
  75. /**
  76. * Indicate cipher
  77. *
  78. * @var int
  79. */
  80. protected $cipher = self::CIPHER_LATEST;
  81. /**
  82. * Version of encryption key
  83. *
  84. * @var int
  85. */
  86. protected $keyVersion;
  87. /**
  88. * Array of encryption keys
  89. *
  90. * @var string[]
  91. */
  92. protected $keys = [];
  93. /**
  94. * @var Random
  95. */
  96. private $random;
  97. /**
  98. * @var KeyValidator
  99. */
  100. private $keyValidator;
  101. /**
  102. * Encryptor constructor.
  103. * @param Random $random
  104. * @param DeploymentConfig $deploymentConfig
  105. * @param KeyValidator|null $keyValidator
  106. */
  107. public function __construct(
  108. Random $random,
  109. DeploymentConfig $deploymentConfig,
  110. KeyValidator $keyValidator = null
  111. ) {
  112. $this->random = $random;
  113. // load all possible keys
  114. $this->keys = preg_split('/\s+/s', trim((string)$deploymentConfig->get(self::PARAM_CRYPT_KEY)));
  115. $this->keyVersion = count($this->keys) - 1;
  116. $this->keyValidator = $keyValidator ?: ObjectManager::getInstance()->get(KeyValidator::class);
  117. }
  118. /**
  119. * Check whether specified cipher version is supported
  120. *
  121. * Returns matched supported version or throws exception
  122. *
  123. * @param int $version
  124. * @return int
  125. * @throws \Exception
  126. */
  127. public function validateCipher($version)
  128. {
  129. $types = [
  130. self::CIPHER_BLOWFISH,
  131. self::CIPHER_RIJNDAEL_128,
  132. self::CIPHER_RIJNDAEL_256,
  133. self::CIPHER_AEAD_CHACHA20POLY1305,
  134. ];
  135. $version = (int)$version;
  136. if (!in_array($version, $types, true)) {
  137. throw new \Exception((string)new \Magento\Framework\Phrase('Not supported cipher version'));
  138. }
  139. return $version;
  140. }
  141. /**
  142. * @inheritdoc
  143. */
  144. public function getHash($password, $salt = false, $version = self::HASH_VERSION_LATEST)
  145. {
  146. if ($salt === false) {
  147. return $this->hash($password, $version);
  148. }
  149. if ($salt === true) {
  150. $salt = self::DEFAULT_SALT_LENGTH;
  151. }
  152. if (is_integer($salt)) {
  153. $salt = $this->random->getRandomString($salt);
  154. }
  155. return implode(
  156. self::DELIMITER,
  157. [
  158. $this->hash($salt . $password, $version),
  159. $salt,
  160. $version
  161. ]
  162. );
  163. }
  164. /**
  165. * @inheritdoc
  166. */
  167. public function hash($data, $version = self::HASH_VERSION_LATEST)
  168. {
  169. return hash($this->hashVersionMap[$version], (string)$data);
  170. }
  171. /**
  172. * @inheritdoc
  173. */
  174. public function validateHash($password, $hash)
  175. {
  176. return $this->isValidHash($password, $hash);
  177. }
  178. /**
  179. * @inheritdoc
  180. */
  181. public function isValidHash($password, $hash)
  182. {
  183. $this->explodePasswordHash($hash);
  184. foreach ($this->getPasswordVersion() as $hashVersion) {
  185. $password = $this->hash($this->getPasswordSalt() . $password, $hashVersion);
  186. }
  187. return Security::compareStrings(
  188. $password,
  189. $this->getPasswordHash()
  190. );
  191. }
  192. /**
  193. * @inheritdoc
  194. */
  195. public function validateHashVersion($hash, $validateCount = false)
  196. {
  197. $this->explodePasswordHash($hash);
  198. $hashVersions = $this->getPasswordVersion();
  199. return $validateCount
  200. ? end($hashVersions) === self::HASH_VERSION_LATEST && count($hashVersions) === 1
  201. : end($hashVersions) === self::HASH_VERSION_LATEST;
  202. }
  203. /**
  204. * Explode password hash
  205. *
  206. * @param string $hash
  207. * @return array
  208. */
  209. private function explodePasswordHash($hash)
  210. {
  211. $explodedPassword = explode(self::DELIMITER, $hash, 3);
  212. foreach ($this->passwordHashMap as $key => $defaultValue) {
  213. $this->passwordHashMap[$key] = (isset($explodedPassword[$key])) ? $explodedPassword[$key] : $defaultValue;
  214. }
  215. return $this->passwordHashMap;
  216. }
  217. /**
  218. * Get password hash
  219. *
  220. * @return string
  221. */
  222. private function getPasswordHash()
  223. {
  224. return (string)$this->passwordHashMap[self::PASSWORD_HASH];
  225. }
  226. /**
  227. * Get password salt
  228. *
  229. * @return string
  230. */
  231. private function getPasswordSalt()
  232. {
  233. return (string)$this->passwordHashMap[self::PASSWORD_SALT];
  234. }
  235. /**
  236. * Get password version
  237. *
  238. * @return array
  239. */
  240. private function getPasswordVersion()
  241. {
  242. return array_map(
  243. 'intval',
  244. explode(
  245. self::DELIMITER,
  246. (string)$this->passwordHashMap[self::PASSWORD_VERSION]
  247. )
  248. );
  249. }
  250. /**
  251. * Prepend key and cipher versions to encrypted data after encrypting
  252. *
  253. * @param string $data
  254. * @return string
  255. */
  256. public function encrypt($data)
  257. {
  258. $crypt = new SodiumChachaIetf($this->keys[$this->keyVersion]);
  259. return $this->keyVersion .
  260. ':' . self::CIPHER_AEAD_CHACHA20POLY1305 .
  261. ':' . base64_encode($crypt->encrypt($data));
  262. }
  263. /**
  264. * Encrypt data using the fastest available algorithm
  265. *
  266. * @param string $data
  267. * @return string
  268. */
  269. public function encryptWithFastestAvailableAlgorithm($data)
  270. {
  271. $crypt = $this->getCrypt();
  272. if (null === $crypt) {
  273. return $data;
  274. }
  275. return $this->keyVersion .
  276. ':' . $this->getCipherVersion() .
  277. ':' . base64_encode($crypt->encrypt($data));
  278. }
  279. /**
  280. * Look for key and crypt versions in encrypted data before decrypting
  281. *
  282. * Unsupported/unspecified key version silently fallback to the oldest we have
  283. * Unsupported cipher versions eventually throw exception
  284. * Unspecified cipher version fallback to the oldest we support
  285. *
  286. * @param string $data
  287. * @return string
  288. * @throws \Exception
  289. */
  290. public function decrypt($data)
  291. {
  292. if ($data) {
  293. $parts = explode(':', $data, 4);
  294. $partsCount = count($parts);
  295. $initVector = null;
  296. // specified key, specified crypt, specified iv
  297. if (4 === $partsCount) {
  298. list($keyVersion, $cryptVersion, $iv, $data) = $parts;
  299. $initVector = $iv ? $iv : null;
  300. $keyVersion = (int)$keyVersion;
  301. $cryptVersion = self::CIPHER_RIJNDAEL_256;
  302. // specified key, specified crypt
  303. } elseif (3 === $partsCount) {
  304. list($keyVersion, $cryptVersion, $data) = $parts;
  305. $keyVersion = (int)$keyVersion;
  306. $cryptVersion = (int)$cryptVersion;
  307. // no key version = oldest key, specified crypt
  308. } elseif (2 === $partsCount) {
  309. list($cryptVersion, $data) = $parts;
  310. $keyVersion = 0;
  311. $cryptVersion = (int)$cryptVersion;
  312. // no key version = oldest key, no crypt version = oldest crypt
  313. } elseif (1 === $partsCount) {
  314. $keyVersion = 0;
  315. $cryptVersion = self::CIPHER_BLOWFISH;
  316. // not supported format
  317. } else {
  318. return '';
  319. }
  320. // no key for decryption
  321. if (!isset($this->keys[$keyVersion])) {
  322. return '';
  323. }
  324. $crypt = $this->getCrypt($this->keys[$keyVersion], $cryptVersion, $initVector);
  325. if (null === $crypt) {
  326. return '';
  327. }
  328. return trim($crypt->decrypt(base64_decode((string)$data)));
  329. }
  330. return '';
  331. }
  332. /**
  333. * Validate key contains only allowed characters
  334. *
  335. * @param string|null $key NULL value means usage of the default key specified on constructor
  336. * @throws \Exception
  337. */
  338. public function validateKey($key)
  339. {
  340. if (!$this->keyValidator->isValid($key)) {
  341. throw new \Exception(
  342. (string)new \Magento\Framework\Phrase(
  343. 'Encryption key must be 32 character string without any white space.'
  344. )
  345. );
  346. }
  347. }
  348. /**
  349. * Attempt to append new key & version
  350. *
  351. * @param string $key
  352. * @return $this
  353. * @throws \Exception
  354. */
  355. public function setNewKey($key)
  356. {
  357. $this->validateKey($key);
  358. $this->keys[] = $key;
  359. $this->keyVersion += 1;
  360. return $this;
  361. }
  362. /**
  363. * Export current keys as string
  364. *
  365. * @return string
  366. */
  367. public function exportKeys()
  368. {
  369. return implode("\n", $this->keys);
  370. }
  371. /**
  372. * Initialize crypt module if needed
  373. *
  374. * By default initializes with latest key and crypt versions
  375. *
  376. * @param string $key
  377. * @param int $cipherVersion
  378. * @param string $initVector
  379. * @return EncryptionAdapterInterface|null
  380. * @throws \Exception
  381. */
  382. private function getCrypt(
  383. string $key = null,
  384. int $cipherVersion = null,
  385. string $initVector = null
  386. ): ?EncryptionAdapterInterface {
  387. if (null === $key && null === $cipherVersion) {
  388. $cipherVersion = $this->getCipherVersion();
  389. }
  390. if (null === $key) {
  391. $key = $this->keys[$this->keyVersion];
  392. }
  393. if (!$key) {
  394. return null;
  395. }
  396. if (null === $cipherVersion) {
  397. $cipherVersion = $this->cipher;
  398. }
  399. $cipherVersion = $this->validateCipher($cipherVersion);
  400. if ($cipherVersion >= self::CIPHER_AEAD_CHACHA20POLY1305) {
  401. return new SodiumChachaIetf($key);
  402. }
  403. if ($cipherVersion === self::CIPHER_RIJNDAEL_128) {
  404. $cipher = MCRYPT_RIJNDAEL_128;
  405. $mode = MCRYPT_MODE_ECB;
  406. } elseif ($cipherVersion === self::CIPHER_RIJNDAEL_256) {
  407. $cipher = MCRYPT_RIJNDAEL_256;
  408. $mode = MCRYPT_MODE_CBC;
  409. } else {
  410. $cipher = MCRYPT_BLOWFISH;
  411. $mode = MCRYPT_MODE_ECB;
  412. }
  413. return new Mcrypt($key, $cipher, $mode, $initVector);
  414. }
  415. /**
  416. * Get cipher version
  417. *
  418. * @return int
  419. */
  420. private function getCipherVersion()
  421. {
  422. if (extension_loaded('sodium')) {
  423. return $this->cipher;
  424. } else {
  425. return self::CIPHER_RIJNDAEL_256;
  426. }
  427. }
  428. }