PHP提供了多种加密和解密的函数,常用的有md5、sha1、base64和openssl等。以下是简单介绍:
md5算法是一种单向加密算法,可以将任意长度的数据加密成一个128位的哈希值,不可逆。
$password = '123456';
$encrypted_password = md5($password);
echo $encrypted_password;
输出结果为:
e10adc3949ba59abbe56e057f20f883e
sha1算法也是一种单向加密算法,可以将任意长度的数据加密成一个160位的哈希值,不可逆。
$password = '123456';
$encrypted_password = sha1($password);
echo $encrypted_password;
输出结果为:
7c4a8d09ca3762af61e59520943dc26494f8941b
base64是一种编码方式,可以将二进制数据编码成可打印的ASCII字符,常用于在网络传输中传递二进制数据。base64编码不是加密,但可以用于加密。
使用base64进行加密:
$data = 'hello world';
$encrypted_data = base64_encode($data);
echo $encrypted_data;
输出结果为:
aGVsbG8gd29ybGQ=
使用base64进行解密:
$encrypted_data = 'aGVsbG8gd29ybGQ=';
$data = base64_decode($encrypted_data);
echo $data;
输出结果为:
hello world
openssl是一个开源的加密库,提供了多种加密和解密算法,包括对称加密和非对称加密。以下是使用openssl进行对称加密和解密的示例:
使用openssl进行对称加密:
$data = 'hello world';
$key = '1234567890';
$cipher = 'aes-128-cbc';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted_data = openssl_encrypt($data, $cipher, $key, 0, $iv);
echo $encrypted_data;
输出结果为:
3rJtVYhQ2yW0JGx0zRdCwA==
使用openssl进行对称解密:
$encrypted_data = '3rJtVYhQ2yW0JGx0zRdCwA==';
$key = '1234567890';
$cipher = 'aes-128-cbc';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$data = openssl_decrypt($encrypted_data, $cipher, $key, 0, $iv);
echo $data;
输出结果为:
hello world