@@ -178,12 +178,13 @@ public function initialize(array $params = [])
178178 throw new EncryptionException ("Unknown digest ' " . $ params ['digest ' ] . "' specified. " );
179179
180180 // Check for valid encoding
181- if (! empty ($ param ['encoding ' ]))
182- if (! in_array ($ params ['encoding ' ],$ this ->encodings ))
181+ if ( ! empty ($ param ['encoding ' ]))
182+ if ( ! in_array ($ params ['encoding ' ], $ this ->encodings ))
183183 throw new EncryptionException ("Unknown encoding ' " . $ params ['encoding ' ] . "' specified. " );
184184
185185 // Derive a secret key for the encrypter
186- $ params ['secret ' ] = bin2hex (\hash_hkdf ($ this ->digest , $ params ['key ' ]));
186+ $ hmacKey = strcmp (phpversion (), '7.1.2 ' ) >= 0 ? \hash_hkdf ($ this ->digest , $ params ['key ' ]) : $ this ->hkdf ($ params ['key ' ], $ this ->digest );
187+ $ params ['secret ' ] = bin2hex ($ hmacKey );
187188
188189 $ handlerName = 'CodeIgniter \\Encryption \\Handlers \\' . $ this ->driver . 'Handler ' ;
189190 $ this ->encrypter = new $ handlerName ($ params );
@@ -269,4 +270,48 @@ protected static function strlen($str)
269270 return mb_strlen ($ str , '8bit ' );
270271 }
271272
273+ // --------------------------------------------------------------------
274+
275+ /**
276+ * HKDF legacy implementation, from CodeIgniter3.
277+ *
278+ * Fallback if PHP version < 7.1.2
279+ *
280+ * @link https://tools.ietf.org/rfc/rfc5869.txt
281+ * @param $key Input key
282+ * @param $digest A SHA-2 hashing algorithm
283+ * @param $salt Optional salt
284+ * @param $length Output length (defaults to the selected digest size)
285+ * @param $info Optional context/application-specific info
286+ * @return string A pseudo-random key
287+ */
288+ public function hkdf ($ key , $ digest = 'sha512 ' , $ salt = null , $ length = null , $ info = '' )
289+ {
290+ if ( ! isset ($ this ->digests [$ digest ]))
291+ {
292+ return false ;
293+ }
294+
295+ if (empty ($ length ) OR ! is_int ($ length ))
296+ {
297+ $ length = $ this ->digests [$ digest ];
298+ }
299+ elseif ($ length > (255 * $ this ->digests [$ digest ]))
300+ {
301+ return false ;
302+ }
303+
304+ self ::strlen ($ salt ) OR $ salt = str_repeat ("\0" , $ this ->digests [$ digest ]);
305+
306+ $ prk = hash_hmac ($ digest , $ key , $ salt , true );
307+ $ key = '' ;
308+ for ($ key_block = '' , $ block_index = 1 ; self ::strlen ($ key ) < $ length ; $ block_index ++ )
309+ {
310+ $ key_block = hash_hmac ($ digest , $ key_block . $ info . chr ($ block_index ), $ prk , true );
311+ $ key .= $ key_block ;
312+ }
313+
314+ return self ::substr ($ key , 0 , $ length );
315+ }
316+
272317}
0 commit comments