PHP中的常见加密函数及其实现方式
发布时间:2023-06-10 12:18:18
PHP中常见的加密函数有很多,包括哈希函数、对称加密、非对称加密等等。
1. 哈希函数
哈希函数是将任意大小的输入数据转化为固定大小的输出的算法。在PHP中,常用的哈希函数有md5()和sha1()。其中,md5()将输入数据转化为128位的输出,sha1()将输入数据转化为160位的输出。这两个函数都是无法逆推的,也就是说无法通过输出反推输入,但是有可能通过碰撞的方式得到相同的输出。
例如:
$text = 'abc123'; $md5 = md5($text); $sha1 = sha1($text); echo $md5." "; // 输出:e99a18c428cb38d5f260853678922e03 echo $sha1; // 输出:6367c48dd193d56ea7b0baad25b19455e529f5ee
2. 对称加密
对称加密是指使用同一个密钥来进行加密和解密的加密方式。在PHP中,常用的对称加密算法是AES(Advanced Encryption Standard)。
例如:
$text = 'abc123'; $key = 'mykey'; $cipher = 'aes-128-cbc'; $iv = '1234567890123456'; $encrypted = openssl_encrypt($text, $cipher, $key, OPENSSL_RAW_DATA, $iv); $decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_RAW_DATA, $iv); echo $encrypted." "; // 输出:??.P?g???9)? echo $decrypted; // 输出:abc123
3. 非对称加密
非对称加密是指使用一对密钥来进行加密和解密的加密方式。在PHP中,常用的非对称加密算法是RSA(Rivest-Shamir-Adleman)。
例如:
$text = 'abc123';
$private_key = openssl_pkey_get_private(file_get_contents('private.key'));
$public_key = openssl_pkey_get_public(file_get_contents('public.key'));
openssl_public_encrypt($text, $encrypted, $public_key);
openssl_private_decrypt($encrypted, $decrypted, $private_key);
echo $encrypted."
"; // 输出:^SD=???0?~:?)??E
echo $decrypted; // 输出:abc123
4. 其他加密函数
除了上述三种加密方式外,PHP还提供了很多其他的加密函数,包括密码散列函数password_hash()和password_verify()、加密文件函数openssl_seal()和openssl_open()、摘要函数hash()等等。
例如:
$text = 'abc123';
$hash = password_hash($text, PASSWORD_DEFAULT);
var_dump(password_verify($text, $hash)); // 输出:bool(true)
$file = 'file.txt';
$encrypted_file = 'file_encrypted';
openssl_seal(file_get_contents($file), $sealed, $ekeys, [$public_key]);
file_put_contents($encrypted_file, $sealed);
openssl_open(file_get_contents($encrypted_file), $decrypted, $ekeys[0], $private_key);
echo $decrypted; // 输出:abc123
$text = 'abc123';
$hash = hash('sha512', $text);
echo $hash; // 输出:7c4a8d09ca3762af61e59520943dc26494f8941b2d7f6f073ef4764dd5e39660...
总结:
PHP提供了非常多的加密函数,可以满足大部分加密需求。需要根据实际需求选择不同的加密算法,注意保护好密钥和加密数据,防止数据泄露。
