Crypt.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Clark Tomlinson <fallen013@gmail.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Stefan Weiberg <sweiberg@suse.com>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\Encryption\Crypto;
  32. use OC\Encryption\Exceptions\DecryptionFailedException;
  33. use OC\Encryption\Exceptions\EncryptionFailedException;
  34. use OC\ServerNotAvailableException;
  35. use OCA\Encryption\Exceptions\MultiKeyDecryptException;
  36. use OCA\Encryption\Exceptions\MultiKeyEncryptException;
  37. use OCP\Encryption\Exceptions\GenericEncryptionException;
  38. use OCP\IConfig;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  41. use OCP\IUserSession;
  42. /**
  43. * Class Crypt provides the encryption implementation of the default Nextcloud
  44. * encryption module. As default AES-256-CTR is used, it does however offer support
  45. * for the following modes:
  46. *
  47. * - AES-256-CTR
  48. * - AES-128-CTR
  49. * - AES-256-CFB
  50. * - AES-128-CFB
  51. *
  52. * For integrity protection Encrypt-Then-MAC using HMAC-SHA256 is used.
  53. *
  54. * @package OCA\Encryption\Crypto
  55. */
  56. class Crypt {
  57. public const SUPPORTED_CIPHERS_AND_KEY_SIZE = [
  58. 'AES-256-CTR' => 32,
  59. 'AES-128-CTR' => 16,
  60. 'AES-256-CFB' => 32,
  61. 'AES-128-CFB' => 16,
  62. ];
  63. // one out of SUPPORTED_CIPHERS_AND_KEY_SIZE
  64. public const DEFAULT_CIPHER = 'AES-256-CTR';
  65. // default cipher from old Nextcloud versions
  66. public const LEGACY_CIPHER = 'AES-128-CFB';
  67. public const SUPPORTED_KEY_FORMATS = ['hash', 'password'];
  68. // one out of SUPPORTED_KEY_FORMATS
  69. public const DEFAULT_KEY_FORMAT = 'hash';
  70. // default key format, old Nextcloud version encrypted the private key directly
  71. // with the user password
  72. public const LEGACY_KEY_FORMAT = 'password';
  73. public const HEADER_START = 'HBEGIN';
  74. public const HEADER_END = 'HEND';
  75. /** @var ILogger */
  76. private $logger;
  77. /** @var string */
  78. private $user;
  79. /** @var IConfig */
  80. private $config;
  81. /** @var IL10N */
  82. private $l;
  83. /** @var string|null */
  84. private $currentCipher;
  85. /** @var bool */
  86. private $supportLegacy;
  87. /**
  88. * @param ILogger $logger
  89. * @param IUserSession $userSession
  90. * @param IConfig $config
  91. * @param IL10N $l
  92. */
  93. public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
  94. $this->logger = $logger;
  95. $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
  96. $this->config = $config;
  97. $this->l = $l;
  98. $this->supportLegacy = $this->config->getSystemValueBool('encryption.legacy_format_support', false);
  99. }
  100. /**
  101. * create new private/public key-pair for user
  102. *
  103. * @return array|bool
  104. */
  105. public function createKeyPair() {
  106. $log = $this->logger;
  107. $res = $this->getOpenSSLPKey();
  108. if (!$res) {
  109. $log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
  110. ['app' => 'encryption']);
  111. if (openssl_error_string()) {
  112. $log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
  113. ['app' => 'encryption']);
  114. }
  115. } elseif (openssl_pkey_export($res,
  116. $privateKey,
  117. null,
  118. $this->getOpenSSLConfig())) {
  119. $keyDetails = openssl_pkey_get_details($res);
  120. $publicKey = $keyDetails['key'];
  121. return [
  122. 'publicKey' => $publicKey,
  123. 'privateKey' => $privateKey
  124. ];
  125. }
  126. $log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
  127. ['app' => 'encryption']);
  128. if (openssl_error_string()) {
  129. $log->error('Encryption Library:' . openssl_error_string(),
  130. ['app' => 'encryption']);
  131. }
  132. return false;
  133. }
  134. /**
  135. * Generates a new private key
  136. *
  137. * @return resource
  138. */
  139. public function getOpenSSLPKey() {
  140. $config = $this->getOpenSSLConfig();
  141. return openssl_pkey_new($config);
  142. }
  143. /**
  144. * get openSSL Config
  145. *
  146. * @return array
  147. */
  148. private function getOpenSSLConfig() {
  149. $config = ['private_key_bits' => 4096];
  150. $config = array_merge(
  151. $config,
  152. $this->config->getSystemValue('openssl', [])
  153. );
  154. return $config;
  155. }
  156. /**
  157. * @param string $plainContent
  158. * @param string $passPhrase
  159. * @param int $version
  160. * @param int $position
  161. * @return false|string
  162. * @throws EncryptionFailedException
  163. */
  164. public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
  165. if (!$plainContent) {
  166. $this->logger->error('Encryption Library, symmetrical encryption failed no content given',
  167. ['app' => 'encryption']);
  168. return false;
  169. }
  170. $iv = $this->generateIv();
  171. $encryptedContent = $this->encrypt($plainContent,
  172. $iv,
  173. $passPhrase,
  174. $this->getCipher());
  175. // Create a signature based on the key as well as the current version
  176. $sig = $this->createSignature($encryptedContent, $passPhrase.'_'.$version.'_'.$position);
  177. // combine content to encrypt the IV identifier and actual IV
  178. $catFile = $this->concatIV($encryptedContent, $iv);
  179. $catFile = $this->concatSig($catFile, $sig);
  180. return $this->addPadding($catFile);
  181. }
  182. /**
  183. * generate header for encrypted file
  184. *
  185. * @param string $keyFormat see SUPPORTED_KEY_FORMATS
  186. * @return string
  187. * @throws \InvalidArgumentException
  188. */
  189. public function generateHeader($keyFormat = self::DEFAULT_KEY_FORMAT) {
  190. if (in_array($keyFormat, self::SUPPORTED_KEY_FORMATS, true) === false) {
  191. throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
  192. }
  193. $cipher = $this->getCipher();
  194. $header = self::HEADER_START
  195. . ':cipher:' . $cipher
  196. . ':keyFormat:' . $keyFormat
  197. . ':' . self::HEADER_END;
  198. return $header;
  199. }
  200. /**
  201. * @param string $plainContent
  202. * @param string $iv
  203. * @param string $passPhrase
  204. * @param string $cipher
  205. * @return string
  206. * @throws EncryptionFailedException
  207. */
  208. private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
  209. $encryptedContent = openssl_encrypt($plainContent,
  210. $cipher,
  211. $passPhrase,
  212. false,
  213. $iv);
  214. if (!$encryptedContent) {
  215. $error = 'Encryption (symmetric) of content failed';
  216. $this->logger->error($error . openssl_error_string(),
  217. ['app' => 'encryption']);
  218. throw new EncryptionFailedException($error);
  219. }
  220. return $encryptedContent;
  221. }
  222. /**
  223. * return cipher either from config.php or the default cipher defined in
  224. * this class
  225. *
  226. * @return string
  227. */
  228. private function getCachedCipher() {
  229. if (isset($this->currentCipher)) {
  230. return $this->currentCipher;
  231. }
  232. // Get cipher either from config.php or the default cipher defined in this class
  233. $cipher = $this->config->getSystemValue('cipher', self::DEFAULT_CIPHER);
  234. if (!isset(self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher])) {
  235. $this->logger->warning(
  236. sprintf(
  237. 'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
  238. $cipher,
  239. self::DEFAULT_CIPHER
  240. ),
  241. ['app' => 'encryption']
  242. );
  243. $cipher = self::DEFAULT_CIPHER;
  244. }
  245. // Remember current cipher to avoid frequent lookups
  246. $this->currentCipher = $cipher;
  247. return $this->currentCipher;
  248. }
  249. /**
  250. * return current encryption cipher
  251. *
  252. * @return string
  253. */
  254. public function getCipher() {
  255. return $this->getCachedCipher();
  256. }
  257. /**
  258. * get key size depending on the cipher
  259. *
  260. * @param string $cipher
  261. * @return int
  262. * @throws \InvalidArgumentException
  263. */
  264. protected function getKeySize($cipher) {
  265. if (isset(self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher])) {
  266. return self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher];
  267. }
  268. throw new \InvalidArgumentException(
  269. sprintf(
  270. 'Unsupported cipher (%s) defined.',
  271. $cipher
  272. )
  273. );
  274. }
  275. /**
  276. * get legacy cipher
  277. *
  278. * @return string
  279. */
  280. public function getLegacyCipher() {
  281. if (!$this->supportLegacy) {
  282. throw new ServerNotAvailableException('Legacy cipher is no longer supported!');
  283. }
  284. return self::LEGACY_CIPHER;
  285. }
  286. /**
  287. * @param string $encryptedContent
  288. * @param string $iv
  289. * @return string
  290. */
  291. private function concatIV($encryptedContent, $iv) {
  292. return $encryptedContent . '00iv00' . $iv;
  293. }
  294. /**
  295. * @param string $encryptedContent
  296. * @param string $signature
  297. * @return string
  298. */
  299. private function concatSig($encryptedContent, $signature) {
  300. return $encryptedContent . '00sig00' . $signature;
  301. }
  302. /**
  303. * Note: This is _NOT_ a padding used for encryption purposes. It is solely
  304. * used to achieve the PHP stream size. It has _NOTHING_ to do with the
  305. * encrypted content and is not used in any crypto primitive.
  306. *
  307. * @param string $data
  308. * @return string
  309. */
  310. private function addPadding($data) {
  311. return $data . 'xxx';
  312. }
  313. /**
  314. * generate password hash used to encrypt the users private key
  315. *
  316. * @param string $password
  317. * @param string $cipher
  318. * @param string $uid only used for user keys
  319. * @return string
  320. */
  321. protected function generatePasswordHash($password, $cipher, $uid = '') {
  322. $instanceId = $this->config->getSystemValue('instanceid');
  323. $instanceSecret = $this->config->getSystemValue('secret');
  324. $salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
  325. $keySize = $this->getKeySize($cipher);
  326. $hash = hash_pbkdf2(
  327. 'sha256',
  328. $password,
  329. $salt,
  330. 100000,
  331. $keySize,
  332. true
  333. );
  334. return $hash;
  335. }
  336. /**
  337. * encrypt private key
  338. *
  339. * @param string $privateKey
  340. * @param string $password
  341. * @param string $uid for regular users, empty for system keys
  342. * @return false|string
  343. */
  344. public function encryptPrivateKey($privateKey, $password, $uid = '') {
  345. $cipher = $this->getCipher();
  346. $hash = $this->generatePasswordHash($password, $cipher, $uid);
  347. $encryptedKey = $this->symmetricEncryptFileContent(
  348. $privateKey,
  349. $hash,
  350. 0,
  351. 0
  352. );
  353. return $encryptedKey;
  354. }
  355. /**
  356. * @param string $privateKey
  357. * @param string $password
  358. * @param string $uid for regular users, empty for system keys
  359. * @return false|string
  360. */
  361. public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
  362. $header = $this->parseHeader($privateKey);
  363. if (isset($header['cipher'])) {
  364. $cipher = $header['cipher'];
  365. } else {
  366. $cipher = $this->getLegacyCipher();
  367. }
  368. if (isset($header['keyFormat'])) {
  369. $keyFormat = $header['keyFormat'];
  370. } else {
  371. $keyFormat = self::LEGACY_KEY_FORMAT;
  372. }
  373. if ($keyFormat === self::DEFAULT_KEY_FORMAT) {
  374. $password = $this->generatePasswordHash($password, $cipher, $uid);
  375. }
  376. // If we found a header we need to remove it from the key we want to decrypt
  377. if (!empty($header)) {
  378. $privateKey = substr($privateKey,
  379. strpos($privateKey,
  380. self::HEADER_END) + strlen(self::HEADER_END));
  381. }
  382. $plainKey = $this->symmetricDecryptFileContent(
  383. $privateKey,
  384. $password,
  385. $cipher,
  386. 0
  387. );
  388. if ($this->isValidPrivateKey($plainKey) === false) {
  389. return false;
  390. }
  391. return $plainKey;
  392. }
  393. /**
  394. * check if it is a valid private key
  395. *
  396. * @param string $plainKey
  397. * @return bool
  398. */
  399. protected function isValidPrivateKey($plainKey) {
  400. $res = openssl_get_privatekey($plainKey);
  401. // TODO: remove resource check one php7.4 is not longer supported
  402. if (is_resource($res) || (is_object($res) && get_class($res) === 'OpenSSLAsymmetricKey')) {
  403. $sslInfo = openssl_pkey_get_details($res);
  404. if (isset($sslInfo['key'])) {
  405. return true;
  406. }
  407. }
  408. return false;
  409. }
  410. /**
  411. * @param string $keyFileContents
  412. * @param string $passPhrase
  413. * @param string $cipher
  414. * @param int $version
  415. * @param int|string $position
  416. * @return string
  417. * @throws DecryptionFailedException
  418. */
  419. public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0) {
  420. if ($keyFileContents == '') {
  421. return '';
  422. }
  423. $catFile = $this->splitMetaData($keyFileContents, $cipher);
  424. if ($catFile['signature'] !== false) {
  425. try {
  426. // First try the new format
  427. $this->checkSignature($catFile['encrypted'], $passPhrase . '_' . $version . '_' . $position, $catFile['signature']);
  428. } catch (GenericEncryptionException $e) {
  429. // For compatibility with old files check the version without _
  430. $this->checkSignature($catFile['encrypted'], $passPhrase . $version . $position, $catFile['signature']);
  431. }
  432. }
  433. return $this->decrypt($catFile['encrypted'],
  434. $catFile['iv'],
  435. $passPhrase,
  436. $cipher);
  437. }
  438. /**
  439. * check for valid signature
  440. *
  441. * @param string $data
  442. * @param string $passPhrase
  443. * @param string $expectedSignature
  444. * @throws GenericEncryptionException
  445. */
  446. private function checkSignature($data, $passPhrase, $expectedSignature) {
  447. $enforceSignature = !$this->config->getSystemValue('encryption_skip_signature_check', false);
  448. $signature = $this->createSignature($data, $passPhrase);
  449. $isCorrectHash = hash_equals($expectedSignature, $signature);
  450. if (!$isCorrectHash && $enforceSignature) {
  451. throw new GenericEncryptionException('Bad Signature', $this->l->t('Bad Signature'));
  452. } elseif (!$isCorrectHash && !$enforceSignature) {
  453. $this->logger->info("Signature check skipped", ['app' => 'encryption']);
  454. }
  455. }
  456. /**
  457. * create signature
  458. *
  459. * @param string $data
  460. * @param string $passPhrase
  461. * @return string
  462. */
  463. private function createSignature($data, $passPhrase) {
  464. $passPhrase = hash('sha512', $passPhrase . 'a', true);
  465. return hash_hmac('sha256', $data, $passPhrase);
  466. }
  467. /**
  468. * remove padding
  469. *
  470. * @param string $padded
  471. * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
  472. * @return string|false
  473. */
  474. private function removePadding($padded, $hasSignature = false) {
  475. if ($hasSignature === false && substr($padded, -2) === 'xx') {
  476. return substr($padded, 0, -2);
  477. } elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
  478. return substr($padded, 0, -3);
  479. }
  480. return false;
  481. }
  482. /**
  483. * split meta data from encrypted file
  484. * Note: for now, we assume that the meta data always start with the iv
  485. * followed by the signature, if available
  486. *
  487. * @param string $catFile
  488. * @param string $cipher
  489. * @return array
  490. */
  491. private function splitMetaData($catFile, $cipher) {
  492. if ($this->hasSignature($catFile, $cipher)) {
  493. $catFile = $this->removePadding($catFile, true);
  494. $meta = substr($catFile, -93);
  495. $iv = substr($meta, strlen('00iv00'), 16);
  496. $sig = substr($meta, 22 + strlen('00sig00'));
  497. $encrypted = substr($catFile, 0, -93);
  498. } else {
  499. $catFile = $this->removePadding($catFile);
  500. $meta = substr($catFile, -22);
  501. $iv = substr($meta, -16);
  502. $sig = false;
  503. $encrypted = substr($catFile, 0, -22);
  504. }
  505. return [
  506. 'encrypted' => $encrypted,
  507. 'iv' => $iv,
  508. 'signature' => $sig
  509. ];
  510. }
  511. /**
  512. * check if encrypted block is signed
  513. *
  514. * @param string $catFile
  515. * @param string $cipher
  516. * @return bool
  517. * @throws GenericEncryptionException
  518. */
  519. private function hasSignature($catFile, $cipher) {
  520. $skipSignatureCheck = $this->config->getSystemValue('encryption_skip_signature_check', false);
  521. $meta = substr($catFile, -93);
  522. $signaturePosition = strpos($meta, '00sig00');
  523. // If we no longer support the legacy format then everything needs a signature
  524. if (!$skipSignatureCheck && !$this->supportLegacy && $signaturePosition === false) {
  525. throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
  526. }
  527. // Enforce signature for the new 'CTR' ciphers
  528. if (!$skipSignatureCheck && $signaturePosition === false && stripos($cipher, 'ctr') !== false) {
  529. throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
  530. }
  531. return ($signaturePosition !== false);
  532. }
  533. /**
  534. * @param string $encryptedContent
  535. * @param string $iv
  536. * @param string $passPhrase
  537. * @param string $cipher
  538. * @return string
  539. * @throws DecryptionFailedException
  540. */
  541. private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
  542. $plainContent = openssl_decrypt($encryptedContent,
  543. $cipher,
  544. $passPhrase,
  545. false,
  546. $iv);
  547. if ($plainContent) {
  548. return $plainContent;
  549. } else {
  550. throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
  551. }
  552. }
  553. /**
  554. * @param string $data
  555. * @return array
  556. */
  557. protected function parseHeader($data) {
  558. $result = [];
  559. if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
  560. $endAt = strpos($data, self::HEADER_END);
  561. $header = substr($data, 0, $endAt + strlen(self::HEADER_END));
  562. // +1 not to start with an ':' which would result in empty element at the beginning
  563. $exploded = explode(':',
  564. substr($header, strlen(self::HEADER_START) + 1));
  565. $element = array_shift($exploded);
  566. while ($element !== self::HEADER_END) {
  567. $result[$element] = array_shift($exploded);
  568. $element = array_shift($exploded);
  569. }
  570. }
  571. return $result;
  572. }
  573. /**
  574. * generate initialization vector
  575. *
  576. * @return string
  577. * @throws GenericEncryptionException
  578. */
  579. private function generateIv() {
  580. return random_bytes(16);
  581. }
  582. /**
  583. * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
  584. * as file key
  585. *
  586. * @return string
  587. * @throws \Exception
  588. */
  589. public function generateFileKey() {
  590. return random_bytes(32);
  591. }
  592. /**
  593. * @param $encKeyFile
  594. * @param $shareKey
  595. * @param $privateKey
  596. * @return string
  597. * @throws MultiKeyDecryptException
  598. */
  599. public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
  600. if (!$encKeyFile) {
  601. throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
  602. }
  603. if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey, 'RC4')) {
  604. return $plainContent;
  605. } else {
  606. throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
  607. }
  608. }
  609. /**
  610. * @param string $plainContent
  611. * @param array $keyFiles
  612. * @return array
  613. * @throws MultiKeyEncryptException
  614. */
  615. public function multiKeyEncrypt($plainContent, array $keyFiles) {
  616. // openssl_seal returns false without errors if plaincontent is empty
  617. // so trigger our own error
  618. if (empty($plainContent)) {
  619. throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
  620. }
  621. // Set empty vars to be set by openssl by reference
  622. $sealed = '';
  623. $shareKeys = [];
  624. $mappedShareKeys = [];
  625. if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles, 'RC4')) {
  626. $i = 0;
  627. // Ensure each shareKey is labelled with its corresponding key id
  628. foreach ($keyFiles as $userId => $publicKey) {
  629. $mappedShareKeys[$userId] = $shareKeys[$i];
  630. $i++;
  631. }
  632. return [
  633. 'keys' => $mappedShareKeys,
  634. 'data' => $sealed
  635. ];
  636. } else {
  637. throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
  638. }
  639. }
  640. }