How to use PHP functions for data encryption and decryption?
Overview
Data encryption and decryption is an important means of protecting sensitive information. In PHP, we can use some functions to implement data encryption and decryption operations. This article will introduce how to use PHP functions for data encryption and decryption, and provide corresponding code examples.
<?php // 加密函数 function encrypt($data){ $encrypt_data = base64_encode($data); return $encrypt_data; } // 解密函数 function decrypt($encrypt_data){ $data = base64_decode($encrypt_data); return $data; } // 测试加密解密 $original_data = 'Hello, World!'; $encrypted_data = encrypt($original_data); $decrypted_data = decrypt($encrypted_data); echo "Original Data: " . $original_data . "<br>"; echo "Encrypted Data: " . $encrypted_data . "<br>"; echo "Decrypted Data: " . $decrypted_data . "<br>"; ?>
<?php // 加密函数 function encrypt($data, $key){ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encrypted_data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); $encrypted_data = $iv . $encrypted_data; return base64_encode($encrypted_data); } // 解密函数 function decrypt($encrypted_data, $key){ $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $encrypted_data = base64_decode($encrypted_data); $iv = substr($encrypted_data, 0, $iv_size); $encrypted_data = substr($encrypted_data, $iv_size); $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted_data, MCRYPT_MODE_CBC, $iv); return rtrim($data, ""); } // 测试加密解密 $original_data = 'Hello, World!'; $key = 'my-secret-key'; $encrypted_data = encrypt($original_data, $key); $decrypted_data = decrypt($encrypted_data, $key); echo "Original Data: " . $original_data . "<br>"; echo "Encrypted Data: " . $encrypted_data . "<br>"; echo "Decrypted Data: " . $decrypted_data . "<br>"; ?>
Summary
This article introduces the method of using PHP functions for data encryption and decryption, and provides corresponding code examples. Encryption and decryption are important means of protecting sensitive data. It is important to choose appropriate encryption methods and algorithms to avoid information leakage. Using these functions can help us store and transmit sensitive data securely.
The above is the detailed content of How to use PHP functions for data encryption and decryption?. For more information, please follow other related articles on the PHP Chinese website!