在PHP中可以使用以下方法实现加密解密功能:
可以使用PHP内置的加密函数进行加密,最常用的是md5和sha1函数。例如:
$password = 'mypassword';
$encrypted_password = md5($password);
上述代码中,将明文密码 'mypassword' 使用 md5 函数进行加密,加密后的结果存储在 $encrypted_password 变量中。
由于md5和sha1函数是单向加密,无法进行解密。因此,在需要解密的情况下,可以使用以下方法:
其中,对称加密算法需要使用相同的密钥进行加密和解密。非对称加密算法使用公钥进行加密,私钥进行解密。
// 对称加密示例
$key = 'mysecretkey';
$data = 'mydata';
function encrypt($key, $data) {
$iv = openssl_random_pseudo_bytes(16);
$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
return base64_encode($iv . $encrypted_data);
}
function decrypt($key, $encrypted_data) {
$encrypted_data = base64_decode($encrypted_data);
$iv = substr($encrypted_data, 0, 16);
$encrypted_data = substr($encrypted_data, 16);
return openssl_decrypt($encrypted_data, 'AES-256-CBC', $key, 0, $iv);
}
$encrypted_data = encrypt($key, $data);
echo $encrypted_data . "\n";
$decrypted_data = decrypt($key, $encrypted_data);
echo $decrypted_data . "\n";
// 非对称加密示例
$private_key = openssl_pkey_new();
openssl_pkey_export($private_key, $private_key_pem);
$public_key = openssl_pkey_get_details($private_key)['key'];
$data = 'mydata';
function encrypt($data, $public_key) {
openssl_public_encrypt($data, $encrypted_data, $public_key);
return base64_encode($encrypted_data);
}
function decrypt($encrypted_data, $private_key) {
$encrypted_data = base64_decode($encrypted_data);
openssl_private_decrypt($encrypted_data, $decrypted_data, $private_key);
return $decrypted_data;
}
$encrypted_data = encrypt($data, $public_key);
echo $encrypted_data . "\n";
$decrypted_data = decrypt($encrypted_data, $private_key_pem);
echo $decrypted_data . "\n";
上述代码中,对称加密使用的是 AES-256-CBC 算法,非对称加密使用的是 OpenSSL 库。