@@ -84,12 +84,17 @@ public function encrypt($data, $key) {
84
84
}
85
85
}
86
86
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
+
87
92
/* Create IV. */
88
93
$ rnd = $ this ->psl ['crypt/rand ' ];
89
94
$ iv = $ rnd ->bytes (mcrypt_enc_get_iv_size ($ td ));
90
95
91
96
/* Init mcrypt. */
92
- mcrypt_generic_init ($ td , $ key , $ iv );
97
+ mcrypt_generic_init ($ td , $ key1 , $ iv );
93
98
94
99
/* Prepeare the array with data. */
95
100
$ serializedData = serialize ($ data );
@@ -111,7 +116,7 @@ public function encrypt($data, $key) {
111
116
$ encrypted ['iv ' ] = base64_encode ($ iv ); /* Initialization vector, just a bunch of randomness. */
112
117
$ encrypted ['cdata ' ] = base64_encode (mcrypt_generic ($ td , $ serializedData )); /* The encrypted data. */
113
118
$ 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. */
115
120
);
116
121
return json_encode ($ encrypted );
117
122
}
@@ -148,14 +153,19 @@ public function decrypt($data, $key) {
148
153
$ td = mcrypt_module_open ($ data ['algo ' ], '' , $ data ['mode ' ], '' );
149
154
$ block = mcrypt_enc_get_block_size ($ td );
150
155
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
+
151
161
/* 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 )) {
153
163
throw new \phpSec \Exception \GeneralSecurityException ('Message authentication code invalid ' );
154
164
return false ;
155
165
}
156
166
157
167
/* Init mcrypt. */
158
- mcrypt_generic_init ($ td , $ key , base64_decode ($ data ['iv ' ]));
168
+ mcrypt_generic_init ($ td , $ key1 , base64_decode ($ data ['iv ' ]));
159
169
160
170
$ decrypted = rtrim (mdecrypt_generic ($ td , base64_decode ($ this ->stripPadding ($ block , $ data ['cdata ' ]))));
161
171
0 commit comments