Skip to content
Snippets Groups Projects
Unverified Commit 648b60fa authored by lynn-stephenson's avatar lynn-stephenson
Browse files

Derive encryption key & MAC key from a single key.

parent b13d9bcc
No related branches found
No related tags found
No related merge requests found
......@@ -10,6 +10,7 @@ declare(strict_types=1);
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Lynn Stephenson <lynn.stephenson@protonmail.com>
*
* @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.');
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment