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.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 OCP\Security\ISecureRandom;
  33. use phpseclib\Crypt\AES;
  34. use phpseclib\Crypt\Hash;
  35. /**
  36. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  37. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  38. *
  39. * Usage:
  40. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  41. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  42. *
  43. * @package OC\Security
  44. */
  45. class Crypto implements ICrypto {
  46. /** @var AES $cipher */
  47. private $cipher;
  48. /** @var int */
  49. private $ivLength = 16;
  50. /** @var IConfig */
  51. private $config;
  52. /**
  53. * @param IConfig $config
  54. * @param ISecureRandom $random
  55. */
  56. public function __construct(IConfig $config) {
  57. $this->cipher = new AES();
  58. $this->config = $config;
  59. }
  60. /**
  61. * @param string $message The message to authenticate
  62. * @param string $password Password to use (defaults to `secret` in config.php)
  63. * @return string Calculated HMAC
  64. */
  65. public function calculateHMAC(string $message, string $password = ''): string {
  66. if ($password === '') {
  67. $password = $this->config->getSystemValue('secret');
  68. }
  69. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  70. $password = hash('sha512', $password . 'a');
  71. $hash = new Hash('sha512');
  72. $hash->setKey($password);
  73. return $hash->hash($message);
  74. }
  75. /**
  76. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  77. *
  78. * @param string $plaintext
  79. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  80. * @return string Authenticated ciphertext
  81. * @throws Exception if it was not possible to gather sufficient entropy
  82. * @throws Exception if encrypting the data failed
  83. */
  84. public function encrypt(string $plaintext, string $password = ''): string {
  85. if ($password === '') {
  86. $password = $this->config->getSystemValue('secret');
  87. }
  88. $keyMaterial = hash_hkdf('sha512', $password);
  89. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  90. $iv = \random_bytes($this->ivLength);
  91. $this->cipher->setIV($iv);
  92. /** @var string|false $encrypted */
  93. $encrypted = $this->cipher->encrypt($plaintext);
  94. if ($encrypted === false) {
  95. throw new Exception('Encrypting failed.');
  96. }
  97. $ciphertext = bin2hex($encrypted);
  98. $iv = bin2hex($iv);
  99. $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, substr($keyMaterial, 32)));
  100. return $ciphertext.'|'.$iv.'|'.$hmac.'|3';
  101. }
  102. /**
  103. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  104. * @param string $authenticatedCiphertext
  105. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  106. * @return string plaintext
  107. * @throws Exception If the HMAC does not match
  108. * @throws Exception If the decryption failed
  109. */
  110. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  111. if ($password === '') {
  112. $password = $this->config->getSystemValue('secret');
  113. }
  114. $hmacKey = $encryptionKey = $password;
  115. $parts = explode('|', $authenticatedCiphertext);
  116. $partCount = \count($parts);
  117. if ($partCount < 3 || $partCount > 4) {
  118. throw new Exception('Authenticated ciphertext could not be decoded.');
  119. }
  120. $ciphertext = $this->hex2bin($parts[0]);
  121. $iv = $parts[1];
  122. $hmac = $this->hex2bin($parts[2]);
  123. if ($partCount === 4) {
  124. $version = $parts[3];
  125. if ($version >= '2') {
  126. $iv = $this->hex2bin($iv);
  127. }
  128. if ($version === '3') {
  129. $keyMaterial = hash_hkdf('sha512', $password);
  130. $encryptionKey = substr($keyMaterial, 0, 32);
  131. $hmacKey = substr($keyMaterial, 32);
  132. }
  133. }
  134. $this->cipher->setPassword($encryptionKey);
  135. $this->cipher->setIV($iv);
  136. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  137. throw new Exception('HMAC does not match.');
  138. }
  139. $result = $this->cipher->decrypt($ciphertext);
  140. if ($result === false) {
  141. throw new Exception('Decryption failed');
  142. }
  143. return $result;
  144. }
  145. private function hex2bin(string $hex): string {
  146. if (!ctype_xdigit($hex)) {
  147. throw new \RuntimeException('String contains non hex chars: ' . $hex);
  148. }
  149. if (strlen($hex) % 2 !== 0) {
  150. throw new \RuntimeException('Hex string is not of even length: ' . $hex);
  151. }
  152. $result = hex2bin($hex);
  153. if ($result === false) {
  154. throw new \RuntimeException('Hex to bin conversion failed: ' . $hex);
  155. }
  156. return $result;
  157. }
  158. }