Home  >  Article  >  Backend Development  >  Encryption and decryption technology in PHP

Encryption and decryption technology in PHP

王林
王林Original
2023-05-11 08:03:052302browse

PHP is a widely used Web development language, and its encryption and decryption technology is of great significance in data security. This article will introduce encryption and decryption technology in PHP and explore its practical application in web applications.

1. Encryption technology

Encryption technology is a process of converting ordinary text into encrypted text. In PHP, encryption technology is mainly used to ensure the security of transmitted data, such as user login information, transaction data, etc. Common encryption technologies in PHP are as follows:

  1. Hash encryption

Hash encryption is to convert an input of any length (also called a message) through a specific algorithm. For fixed-length output, the algorithm satisfies the following two conditions:

a. For the same input, the algorithm must ensure that the output is the same;
b. For different inputs, the algorithm must ensure that the output is different.

Commonly used hash encryption functions in PHP include md5(), sha1(), etc. The md5() function converts an input string of any length into a 128-bit output and returns it as a 32-bit hexadecimal string.

For example, the following code can convert the string "Hello World" into an encrypted string:

<?php
$orig_str = "Hello World";
$encrypted_str = md5($orig_str);
echo "加密前的字符串:$orig_str <br>";
echo "加密后的字符串:$encrypted_str";
?>
  1. Symmetric encryption

Symmetric encryption It is an encryption technology that uses the same key to encrypt and decrypt data. In PHP, use the mcrypt() function to perform symmetric encryption operations. mcrypt() uses very common encryption algorithms, such as DES, TripleDES, Blowfish, AES, etc.

The following code demonstrates how to use the mcrypt() function for symmetric encryption:

<?php
$key = '0123456789abcdef'; // 密钥
$input = 'Hello World'; // 加密前的字符串
$td = mcrypt_module_open('rijndael-128', '', 'cbc', ''); // 初始化加密模型
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); // 初始化随机向量
mcrypt_generic_init($td, $key, $iv); // 初始化加密
$encrypted = mcrypt_generic($td, $input); // 进行加密操作
mcrypt_generic_deinit($td); // 结束加密
mcrypt_module_close($td); // 关闭加密模型
echo "加密前的字符串: $input <br>";
echo "加密后的字符串: ".base64_encode($encrypted)."<br>"; // 输出加密结果
?>
  1. Asymmetric encryption

Asymmetric encryption is a method of using Different keys are used for encryption and decryption algorithms. The commonly used asymmetric encryption algorithm in PHP is RSA. When using the RSA algorithm for encryption and decryption, two keys, the public key and the private key, are required. Generally, the public key is public, while the private key is known only to the holder.

The following code demonstrates the use of RSA algorithm for encryption and decryption in PHP:

<?php
$data = 'Hello World';
// 生成RSA公钥,并将公钥保存到public.key文件中
$res = openssl_pkey_new();
openssl_pkey_export($res, $privkey); // 生成私钥并保存
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
file_put_contents("public.key", $pubkey);
// 使用RSA公钥加密数据
openssl_public_encrypt($data, $encrypted, $pubkey);
echo "加密前的数据:$data <br>";
echo "加密后的数据:$encrypted <br>";
// 使用RSA私钥解密数据
openssl_pkey_get_private($privkey);
openssl_private_decrypt($encrypted, $decrypted, $privkey);
echo "解密后的数据:$decrypted <br>";
?>

2. Decryption technology

Decryption technology restores encrypted data process. In PHP, decryption technology is mainly used to ensure the security of transmitted data, such as user login information, transaction data, etc. Common decryption technologies in PHP are as follows:

  1. Hash decryption

Hash encryption is an irreversible encryption technology and cannot be decrypted.

  1. Symmetric decryption

Symmetric decryption is an encryption technology that uses the same key to decrypt data. In PHP, use the mcrypt() function to perform symmetric decryption operations.

The following code demonstrates how to use the mcrypt() function for symmetric decryption:

<?php
$key = '0123456789abcdef'; // 密钥
$input = 'vO8v4zinwuL6qvtSRWdq3g=='; // 加密后的字符串
$td = mcrypt_module_open('rijndael-128', '', 'cbc', ''); // 初始化加密模型
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); // 初始化随机向量
mcrypt_generic_init($td, $key, $iv); // 初始化加密
$decrypted = mdecrypt_generic($td, base64_decode($input)); // 进行解密操作
mcrypt_generic_deinit($td); // 结束加密
mcrypt_module_close($td); // 关闭加密模型
echo "解密前的字符串: $input <br>";
echo "解密后的字符串: $decrypted"; // 输出解密结果
?>
  1. Asymmetric decryption

Asymmetric decryption is a way to use Different keys are used for encryption and decryption algorithms. In PHP, the commonly used asymmetric decryption algorithm is RSA.

The following code demonstrates the use of RSA algorithm for decryption in PHP:

<?php
$data = 'Hello World';
// 使用RSA公钥加密数据
$pubkey = file_get_contents("public.key");
openssl_public_encrypt($data, $encrypted, $pubkey);
echo "加密前的数据:$data <br>";
echo "加密后的数据:$encrypted <br>";
// 使用RSA私钥解密数据
$privkey = file_get_contents("private.key");
openssl_private_decrypt($encrypted, $decrypted, $privkey);
echo "解密后的数据:$decrypted <br>";
?>

3. Application examples

In actual Web development, encryption and decryption technology are the guarantee An important means of data security. The following will use a user login application example to demonstrate how to use encryption and decryption technology to protect user login information.

  1. Front-end form

In the front-end page, you need to create a form to obtain the user's login information. The form contains two input boxes for username and password:

<form method="post" action="login.php">
    <label>用户名:</label>
    <input type="text" name="username"><br>
    <label>密码:</label>
    <input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>
  1. Backend login verification

In the PHP code, the username and password entered by the user need to be verified. If the verification is passed, the user's encrypted information can be stored in the Session for use on subsequent pages.

<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
// 数据库连接等相关代码省略
// 检查用户名和密码是否匹配
if ($username == $db_username && $password == $db_password) {
    // 生成加密后的用户信息
    $userinfo = array(
        'username' => $username,
        'password' => $password
    );
    $encrypted = base64_encode(serialize($userinfo));
    // 将加密后的用户信息保存到Session中
    $_SESSION['userinfo'] = $encrypted;
    // 登录成功,跳转到首页
    header("Location: index.php");
} else {
    // 登录失败,返回错误消息
    echo "用户名或密码错误!";
}
?>
  1. Backend homepage

In the backend homepage, the encrypted user information saved in the Session needs to be decrypted and the user name and other information displayed.

<?php
session_start();
if (isset($_SESSION['userinfo'])) {
    // 从Session中获取加密后的用户信息
    $encrypted = $_SESSION['userinfo'];
    // 解密用户信息
    $userinfo = unserialize(base64_decode($encrypted));
    $username = $userinfo['username'];
    echo "欢迎您,$username!";
} else {
    // 用户未登录,跳转到登录页
    header("Location: login.php");
}
?>

To sum up, encryption and decryption technology has important application value in PHP. In the web development process, it is crucial to ensure the security of user data. Developers need to choose appropriate encryption and decryption technologies based on actual needs to enhance data security.

The above is the detailed content of Encryption and decryption technology in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn