以下使用的是對稱式加密(Symmetric Encryption),對稱式加密就是傳送方與接收方的加解密皆使用同一把密鑰,所以只要雙方都擁有這把鑰匙,當傳送方傳資料時,使用這把鑰匙加密,接收方收到訊息後,再用同一把鑰匙解密,就能解開訊息了。
function encrypt($key, $payload)
{
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($payload, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($encrypted . '::' . $iv);
}
function decrypt($key, $garble)
{
list($encrypted_data, $iv) = explode('::', base64_decode($garble), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}
echo $encode = encrypt(key, password); //RkxTT2J5SkVzZm5VTW9FMHViMU1xUT09OjrJfvikoZhWwSxYeErbiroN
echo $decode = decrypt(key, $encode); //password
相關連結:
How To Encrypt And Execute Your PHP Code With MCRYPT Or OPENSSL
基礎密碼學(對稱式與非對稱式加密技術)