From 648b60fa0ed0cd980e6309ddc8939673ca1e159f Mon Sep 17 00:00:00 2001 From: lynn-stephenson Date: Thu, 15 Oct 2020 21:04:38 -0800 Subject: [PATCH] Derive encryption key & MAC key from a single key. Signed-off-by: lynn-stephenson --- lib/private/Security/Crypto.php | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/lib/private/Security/Crypto.php b/lib/private/Security/Crypto.php index 154448281b..35add2dc64 100644 --- a/lib/private/Security/Crypto.php +++ b/lib/private/Security/Crypto.php @@ -10,6 +10,7 @@ declare(strict_types=1); * @author Lukas Reschke * @author Morris Jobke * @author Roeland Jago Douma + * @author Lynn Stephenson * * @license AGPL-3.0 * @@ -90,16 +91,17 @@ class Crypto implements ICrypto { if ($password === '') { $password = $this->config->getSystemValue('secret'); } - $this->cipher->setPassword($password); + $keyMaterial = hash_hkdf('sha512', $password); + $this->cipher->setPassword(substr($keyMaterial, 0, 32)); $iv = \random_bytes($this->ivLength); $this->cipher->setIV($iv); $ciphertext = bin2hex($this->cipher->encrypt($plaintext)); $iv = bin2hex($iv); - $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, $password)); + $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, substr($keyMaterial, 32))); - return $ciphertext.'|'.$iv.'|'.$hmac.'|2'; + return $ciphertext.'|'.$iv.'|'.$hmac.'|3'; } /** @@ -114,7 +116,7 @@ class Crypto implements ICrypto { if ($password === '') { $password = $this->config->getSystemValue('secret'); } - $this->cipher->setPassword($password); + $hmacKey = $encryptionKey = $password; $parts = explode('|', $authenticatedCiphertext); $partCount = \count($parts); @@ -128,14 +130,20 @@ class Crypto implements ICrypto { if ($partCount === 4) { $version = $parts[3]; - if ($version === '2') { + if ($version >= '2') { $iv = hex2bin($iv); } - } + if ($version === '3') { + $keyMaterial = hash_hkdf('sha512', $password); + $encryptionKey = substr($keyMaterial, 0, 32); + $hmacKey = substr($keyMaterial, 32); + } + } + $this->cipher->setPassword($encryptionKey); $this->cipher->setIV($iv); - if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $password), $hmac)) { + if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) { throw new \Exception('HMAC does not match.'); }