PHP шифрование и дешифрование данных
В сайтостроении не обойтись без хранения данных в хранилищах. Так как никто не застрахован от взлома, данные пользвателей не должны попасть в руки хакеров. Для этого все данные в базе должны храниться в зашифрованном виде.
А следующие функции помогут нам в этом.
<?php
define('ENCRYPTION_KEY', 'a77gygb86d144e3f080uyg887b61c7c2e43');
function encrypt($plaintext){
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
return $ciphertext;
}
function decode($ciphertext){
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$plaintext = openssl_decrypt($ciphertext_raw, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
if (hash_equals($hmac, $calcmac))
{
return $plaintext;
}
}
$_one = encrypt("starnetkhv@gmail.com");
echo $_one;
echo decode($_one);



