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 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Lynn Stephenson <lynn.stephenson@protonmail.com>
  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 OCP\IConfig;
  30. use OCP\Security\ICrypto;
  31. use OCP\Security\ISecureRandom;
  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. /** @var AES $cipher */
  46. private $cipher;
  47. /** @var int */
  48. private $ivLength = 16;
  49. /** @var IConfig */
  50. private $config;
  51. /**
  52. * @param IConfig $config
  53. * @param ISecureRandom $random
  54. */
  55. public function __construct(IConfig $config) {
  56. $this->cipher = new AES();
  57. $this->config = $config;
  58. }
  59. /**
  60. * @param string $message The message to authenticate
  61. * @param string $password Password to use (defaults to `secret` in config.php)
  62. * @return string Calculated HMAC
  63. */
  64. public function calculateHMAC(string $message, string $password = ''): string {
  65. if ($password === '') {
  66. $password = $this->config->getSystemValue('secret');
  67. }
  68. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  69. $password = hash('sha512', $password . 'a');
  70. $hash = new Hash('sha512');
  71. $hash->setKey($password);
  72. return $hash->hash($message);
  73. }
  74. /**
  75. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  76. * @param string $plaintext
  77. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  78. * @return string Authenticated ciphertext
  79. */
  80. public function encrypt(string $plaintext, string $password = ''): string {
  81. if ($password === '') {
  82. $password = $this->config->getSystemValue('secret');
  83. }
  84. $keyMaterial = hash_hkdf('sha512', $password);
  85. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  86. $iv = \random_bytes($this->ivLength);
  87. $this->cipher->setIV($iv);
  88. $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
  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 $authenticatedCiphertext
  96. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  97. * @return string plaintext
  98. * @throws \Exception If the HMAC does not match
  99. * @throws \Exception If the decryption failed
  100. */
  101. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  102. if ($password === '') {
  103. $password = $this->config->getSystemValue('secret');
  104. }
  105. $hmacKey = $encryptionKey = $password;
  106. $parts = explode('|', $authenticatedCiphertext);
  107. $partCount = \count($parts);
  108. if ($partCount < 3 || $partCount > 4) {
  109. throw new \Exception('Authenticated ciphertext could not be decoded.');
  110. }
  111. $ciphertext = hex2bin($parts[0]);
  112. $iv = $parts[1];
  113. $hmac = hex2bin($parts[2]);
  114. if ($partCount === 4) {
  115. $version = $parts[3];
  116. if ($version >= '2') {
  117. $iv = hex2bin($iv);
  118. }
  119. if ($version === '3') {
  120. $keyMaterial = hash_hkdf('sha512', $password);
  121. $encryptionKey = substr($keyMaterial, 0, 32);
  122. $hmacKey = substr($keyMaterial, 32);
  123. }
  124. }
  125. $this->cipher->setPassword($encryptionKey);
  126. $this->cipher->setIV($iv);
  127. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  128. throw new \Exception('HMAC does not match.');
  129. }
  130. $result = $this->cipher->decrypt($ciphertext);
  131. if ($result === false) {
  132. throw new \Exception('Decryption failed');
  133. }
  134. return $result;
  135. }
  136. }