Crypto.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Security;
  9. use Exception;
  10. use OCP\IConfig;
  11. use OCP\Security\ICrypto;
  12. use phpseclib\Crypt\AES;
  13. use phpseclib\Crypt\Hash;
  14. /**
  15. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  16. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  17. *
  18. * Usage:
  19. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  20. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  21. *
  22. * @package OC\Security
  23. */
  24. class Crypto implements ICrypto {
  25. private AES $cipher;
  26. private int $ivLength = 16;
  27. public function __construct(
  28. private IConfig $config,
  29. ) {
  30. $this->cipher = new AES();
  31. }
  32. /**
  33. * @param string $message The message to authenticate
  34. * @param string $password Password to use (defaults to `secret` in config.php)
  35. * @return string Calculated HMAC
  36. */
  37. public function calculateHMAC(string $message, string $password = ''): string {
  38. if ($password === '') {
  39. $password = $this->config->getSystemValueString('secret');
  40. }
  41. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  42. $password = hash('sha512', $password . 'a');
  43. $hash = new Hash('sha512');
  44. $hash->setKey($password);
  45. return $hash->hash($message);
  46. }
  47. /**
  48. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  49. *
  50. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  51. * @return string Authenticated ciphertext
  52. * @throws Exception if it was not possible to gather sufficient entropy
  53. * @throws Exception if encrypting the data failed
  54. */
  55. public function encrypt(string $plaintext, string $password = ''): string {
  56. if ($password === '') {
  57. $password = $this->config->getSystemValueString('secret');
  58. }
  59. $keyMaterial = hash_hkdf('sha512', $password);
  60. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  61. $iv = \random_bytes($this->ivLength);
  62. $this->cipher->setIV($iv);
  63. /** @var string|false $encrypted */
  64. $encrypted = $this->cipher->encrypt($plaintext);
  65. if ($encrypted === false) {
  66. throw new Exception('Encrypting failed.');
  67. }
  68. $ciphertext = bin2hex($encrypted);
  69. $iv = bin2hex($iv);
  70. $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, substr($keyMaterial, 32)));
  71. return $ciphertext.'|'.$iv.'|'.$hmac.'|3';
  72. }
  73. /**
  74. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  75. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  76. * @throws Exception If the HMAC does not match
  77. * @throws Exception If the decryption failed
  78. */
  79. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  80. $secret = $this->config->getSystemValue('secret');
  81. try {
  82. if ($password === '') {
  83. return $this->decryptWithoutSecret($authenticatedCiphertext, $secret);
  84. }
  85. return $this->decryptWithoutSecret($authenticatedCiphertext, $password);
  86. } catch (Exception $e) {
  87. if ($password === '') {
  88. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  89. return $this->decryptWithoutSecret($authenticatedCiphertext, '');
  90. }
  91. throw $e;
  92. }
  93. }
  94. private function decryptWithoutSecret(string $authenticatedCiphertext, string $password = ''): string {
  95. $hmacKey = $encryptionKey = $password;
  96. $parts = explode('|', $authenticatedCiphertext);
  97. $partCount = \count($parts);
  98. if ($partCount < 3 || $partCount > 4) {
  99. throw new Exception('Authenticated ciphertext could not be decoded.');
  100. }
  101. $ciphertext = $this->hex2bin($parts[0]);
  102. $iv = $parts[1];
  103. $hmac = $this->hex2bin($parts[2]);
  104. if ($partCount === 4) {
  105. $version = $parts[3];
  106. if ($version >= '2') {
  107. $iv = $this->hex2bin($iv);
  108. }
  109. if ($version === '3') {
  110. $keyMaterial = hash_hkdf('sha512', $password);
  111. $encryptionKey = substr($keyMaterial, 0, 32);
  112. $hmacKey = substr($keyMaterial, 32);
  113. }
  114. }
  115. $this->cipher->setPassword($encryptionKey);
  116. $this->cipher->setIV($iv);
  117. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  118. throw new Exception('HMAC does not match.');
  119. }
  120. $result = $this->cipher->decrypt($ciphertext);
  121. if ($result === false) {
  122. throw new Exception('Decryption failed');
  123. }
  124. return $result;
  125. }
  126. private function hex2bin(string $hex): string {
  127. if (!ctype_xdigit($hex)) {
  128. throw new \RuntimeException('String contains non hex chars: ' . $hex);
  129. }
  130. if (strlen($hex) % 2 !== 0) {
  131. throw new \RuntimeException('Hex string is not of even length: ' . $hex);
  132. }
  133. $result = hex2bin($hex);
  134. if ($result === false) {
  135. throw new \RuntimeException('Hex to bin conversion failed: ' . $hex);
  136. }
  137. return $result;
  138. }
  139. }