Crypto.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Security;
  27. use phpseclib\Crypt\AES;
  28. use phpseclib\Crypt\Hash;
  29. use OCP\Security\ICrypto;
  30. use OCP\Security\ISecureRandom;
  31. use OCP\IConfig;
  32. /**
  33. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  34. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  35. *
  36. * Usage:
  37. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  38. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  39. *
  40. * @package OC\Security
  41. */
  42. class Crypto implements ICrypto {
  43. /** @var AES $cipher */
  44. private $cipher;
  45. /** @var int */
  46. private $ivLength = 16;
  47. /** @var IConfig */
  48. private $config;
  49. /** @var ISecureRandom */
  50. private $random;
  51. /**
  52. * @param IConfig $config
  53. * @param ISecureRandom $random
  54. */
  55. public function __construct(IConfig $config, ISecureRandom $random) {
  56. $this->cipher = new AES();
  57. $this->config = $config;
  58. $this->random = $random;
  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. * @param string $plaintext
  78. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  79. * @return string Authenticated ciphertext
  80. */
  81. public function encrypt(string $plaintext, string $password = ''): string {
  82. if($password === '') {
  83. $password = $this->config->getSystemValue('secret');
  84. }
  85. $this->cipher->setPassword($password);
  86. $iv = $this->random->generate($this->ivLength);
  87. $this->cipher->setIV($iv);
  88. $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
  89. $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, $password));
  90. return $ciphertext.'|'.$iv.'|'.$hmac;
  91. }
  92. /**
  93. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  94. * @param string $authenticatedCiphertext
  95. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  96. * @return string plaintext
  97. * @throws \Exception If the HMAC does not match
  98. */
  99. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  100. if($password === '') {
  101. $password = $this->config->getSystemValue('secret');
  102. }
  103. $this->cipher->setPassword($password);
  104. $parts = explode('|', $authenticatedCiphertext);
  105. if(\count($parts) !== 3) {
  106. throw new \Exception('Authenticated ciphertext could not be decoded.');
  107. }
  108. $ciphertext = hex2bin($parts[0]);
  109. $iv = $parts[1];
  110. $hmac = hex2bin($parts[2]);
  111. $this->cipher->setIV($iv);
  112. if(!hash_equals($this->calculateHMAC($parts[0].$parts[1], $password), $hmac)) {
  113. throw new \Exception('HMAC does not match.');
  114. }
  115. return $this->cipher->decrypt($ciphertext);
  116. }
  117. }