Skip to content
This repository was archived by the owner on Oct 5, 2022. It is now read-only.

Commit ebcc18e

Browse files
committed
Break key into encryption key and HMAC key using pbkdf
1 parent e02f4c4 commit ebcc18e

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

lib/phpSec/Crypt/Crypto.php

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,12 +84,17 @@ public function encrypt($data, $key) {
8484
}
8585
}
8686

87+
/* Using PBKDF with constant salts dedicated to each purpose
88+
* can securely derivce two keys from one */
89+
$key1 = $this->pbkdf2($key, "encrypt", 1, $keySize);
90+
$key2 = $this->pbkdf2($key, "HMAC", 1, $keySize);
91+
8792
/* Create IV. */
8893
$rnd = $this->psl['crypt/rand'];
8994
$iv = $rnd->bytes(mcrypt_enc_get_iv_size($td));
9095

9196
/* Init mcrypt. */
92-
mcrypt_generic_init($td, $key, $iv);
97+
mcrypt_generic_init($td, $key1, $iv);
9398

9499
/* Prepeare the array with data. */
95100
$serializedData = serialize($data);
@@ -111,7 +116,7 @@ public function encrypt($data, $key) {
111116
$encrypted['iv'] = base64_encode($iv); /* Initialization vector, just a bunch of randomness. */
112117
$encrypted['cdata'] = base64_encode(mcrypt_generic($td, $serializedData)); /* The encrypted data. */
113118
$encrypted['mac'] = base64_encode( /* The message authentication code. Used to make sure the */
114-
$this->pbkdf2($encrypted['cdata'], $key, 1, 32) /* message is valid when decrypted. */
119+
$this->pbkdf2($encrypted['cdata'], $key2, 1, 32) /* message is valid when decrypted. */
115120
);
116121
return json_encode($encrypted);
117122
}
@@ -148,14 +153,19 @@ public function decrypt($data, $key) {
148153
$td = mcrypt_module_open($data['algo'], '', $data['mode'], '');
149154
$block = mcrypt_enc_get_block_size($td);
150155

156+
/* Using PBKDF with constant salts dedicated to each purpose
157+
* can securely derivce two keys from one */
158+
$key1 = $this->pbkdf2($key, "encrypt", 1, $keySize);
159+
$key2 = $this->pbkdf2($key, "HMAC", 1, $keySize);
160+
151161
/* Check MAC. */
152-
if(base64_decode($data['mac']) != $this->pbkdf2($data['cdata'], $key, 1, 32)) {
162+
if(base64_decode($data['mac']) != $this->pbkdf2($data['cdata'], $key2, 1, 32)) {
153163
throw new \phpSec\Exception\GeneralSecurityException('Message authentication code invalid');
154164
return false;
155165
}
156166

157167
/* Init mcrypt. */
158-
mcrypt_generic_init($td, $key, base64_decode($data['iv']));
168+
mcrypt_generic_init($td, $key1, base64_decode($data['iv']));
159169

160170
$decrypted = rtrim(mdecrypt_generic($td, base64_decode($this->stripPadding($block, $data['cdata']))));
161171

0 commit comments

Comments
 (0)