You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Crypto.php 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Andreas Fischer <bantu@owncloud.com>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author lynn-stephenson <lynn.stephenson@protonmail.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\Security;
  29. use Exception;
  30. use OCP\IConfig;
  31. use OCP\Security\ICrypto;
  32. use phpseclib\Crypt\AES;
  33. use phpseclib\Crypt\Hash;
  34. /**
  35. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  36. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  37. *
  38. * Usage:
  39. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  40. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  41. *
  42. * @package OC\Security
  43. */
  44. class Crypto implements ICrypto {
  45. private AES $cipher;
  46. private int $ivLength = 16;
  47. public function __construct(
  48. private IConfig $config,
  49. ) {
  50. $this->cipher = new AES();
  51. }
  52. /**
  53. * @param string $message The message to authenticate
  54. * @param string $password Password to use (defaults to `secret` in config.php)
  55. * @return string Calculated HMAC
  56. */
  57. public function calculateHMAC(string $message, string $password = ''): string {
  58. if ($password === '') {
  59. $password = $this->config->getSystemValueString('secret');
  60. }
  61. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  62. $password = hash('sha512', $password . 'a');
  63. $hash = new Hash('sha512');
  64. $hash->setKey($password);
  65. return $hash->hash($message);
  66. }
  67. /**
  68. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  69. *
  70. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  71. * @return string Authenticated ciphertext
  72. * @throws Exception if it was not possible to gather sufficient entropy
  73. * @throws Exception if encrypting the data failed
  74. */
  75. public function encrypt(string $plaintext, string $password = ''): string {
  76. if ($password === '') {
  77. $password = $this->config->getSystemValueString('secret');
  78. }
  79. $keyMaterial = hash_hkdf('sha512', $password);
  80. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  81. $iv = \random_bytes($this->ivLength);
  82. $this->cipher->setIV($iv);
  83. /** @var string|false $encrypted */
  84. $encrypted = $this->cipher->encrypt($plaintext);
  85. if ($encrypted === false) {
  86. throw new Exception('Encrypting failed.');
  87. }
  88. $ciphertext = bin2hex($encrypted);
  89. $iv = bin2hex($iv);
  90. $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, substr($keyMaterial, 32)));
  91. return $ciphertext.'|'.$iv.'|'.$hmac.'|3';
  92. }
  93. /**
  94. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  95. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  96. * @throws Exception If the HMAC does not match
  97. * @throws Exception If the decryption failed
  98. */
  99. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  100. $secret = $this->config->getSystemValue('secret');
  101. try {
  102. if ($password === '') {
  103. return $this->decryptWithoutSecret($authenticatedCiphertext, $secret);
  104. }
  105. return $this->decryptWithoutSecret($authenticatedCiphertext, $password);
  106. } catch (Exception $e) {
  107. if ($password === '') {
  108. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  109. return $this->decryptWithoutSecret($authenticatedCiphertext, '');
  110. }
  111. throw $e;
  112. }
  113. }
  114. private function decryptWithoutSecret(string $authenticatedCiphertext, string $password = ''): string {
  115. $hmacKey = $encryptionKey = $password;
  116. $parts = explode('|', $authenticatedCiphertext);
  117. $partCount = \count($parts);
  118. if ($partCount < 3 || $partCount > 4) {
  119. throw new Exception('Authenticated ciphertext could not be decoded.');
  120. }
  121. $ciphertext = $this->hex2bin($parts[0]);
  122. $iv = $parts[1];
  123. $hmac = $this->hex2bin($parts[2]);
  124. if ($partCount === 4) {
  125. $version = $parts[3];
  126. if ($version >= '2') {
  127. $iv = $this->hex2bin($iv);
  128. }
  129. if ($version === '3') {
  130. $keyMaterial = hash_hkdf('sha512', $password);
  131. $encryptionKey = substr($keyMaterial, 0, 32);
  132. $hmacKey = substr($keyMaterial, 32);
  133. }
  134. }
  135. $this->cipher->setPassword($encryptionKey);
  136. $this->cipher->setIV($iv);
  137. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  138. throw new Exception('HMAC does not match.');
  139. }
  140. $result = $this->cipher->decrypt($ciphertext);
  141. if ($result === false) {
  142. throw new Exception('Decryption failed');
  143. }
  144. return $result;
  145. }
  146. private function hex2bin(string $hex): string {
  147. if (!ctype_xdigit($hex)) {
  148. throw new \RuntimeException('String contains non hex chars: ' . $hex);
  149. }
  150. if (strlen($hex) % 2 !== 0) {
  151. throw new \RuntimeException('Hex string is not of even length: ' . $hex);
  152. }
  153. $result = hex2bin($hex);
  154. if ($result === false) {
  155. throw new \RuntimeException('Hex to bin conversion failed: ' . $hex);
  156. }
  157. return $result;
  158. }
  159. }