欢迎访问宙启技术站
智能推送

PHP加密解密函数,你需要掌握哪些

发布时间:2023-10-07 18:35:09

PHP提供了多种加密解密函数,可以用于保护敏感信息的存储和传输。下面我将介绍一些常用的加密解密函数和一些相关的知识。

一、对称加密

对称加密使用相同的密钥进行加密和解密,加密速度快,适用于大量数据的加密解密。常见的对称加密算法有DES、AES等。

1. 使用DES加密解密:

DES加密算法是对称密钥加密算法,使用相同的密钥进行加密和解密。

加密函数:openssl_encrypt()

解密函数:openssl_decrypt()

示例代码:

$key = '12345678'; // 密钥,8位

$plaintext = 'Hello World!'; // 原始数据

$ciphertext = openssl_encrypt($plaintext, 'DES-ECB', $key, OPENSSL_RAW_DATA);

$decrypted = openssl_decrypt($ciphertext, 'DES-ECB', $key, OPENSSL_RAW_DATA);

echo $ciphertext; // 加密后的数据

echo $decrypted; // 解密后的数据

2. 使用AES加密解密:

AES加密算法是对称密钥加密算法,安全性高。

加密函数:openssl_encrypt()

解密函数:openssl_decrypt()

示例代码:

$key = '1234567890123456'; // 密钥,16位

$plaintext = 'Hello World!'; // 原始数据

$ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);

$decrypted = openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);

echo $ciphertext; // 加密后的数据

echo $decrypted; // 解密后的数据

二、非对称加密

非对称加密使用公钥进行加密,私钥进行解密,安全性更高,可以用于数据的加密和数字签名。

1. 使用RSA加密解密:

RSA加密算法是非对称密钥加密算法,使用公钥进行加密,私钥进行解密。

加密函数:openssl_public_encrypt()

解密函数:openssl_private_decrypt()

示例代码:

// 生成密钥对

$config = array(

    "private_key_bits" => 1024,

);

$res = openssl_pkey_new($config);

openssl_pkey_export($res, $private_key);

$public_key = openssl_pkey_get_details($res)["key"];

$plaintext = 'Hello World!'; // 原始数据

// 加密

openssl_public_encrypt($plaintext, $ciphertext, $public_key);

// 解密

openssl_private_decrypt($ciphertext, $decrypted, $private_key);

echo $ciphertext; // 加密后的数据

echo $decrypted; // 解密后的数据

2. 使用ECC加密解密:

ECC加密算法是非对称密钥加密算法,与RSA相比,密钥长度更短,加解密速度更快。

加密函数:openssl_seal()

解密函数:openssl_open()

示例代码:

// 生成密钥对

$config = array(

    "private_key_type" => OPENSSL_KEYTYPE_EC256,

);

$res = openssl_pkey_new($config);

openssl_pkey_export($res, $private_key);

$public_key = openssl_pkey_get_details($res)["key"];

$plaintext = 'Hello World!'; // 原始数据

// 加密

openssl_seal($plaintext, $sealed_data, $envelope_keys, array($public_key));

// 解密

openssl_open($sealed_data, $decrypted, $envelope_data, $private_key);

echo $sealed_data; // 加密后的数据

echo $decrypted; // 解密后的数据

以上是一些常用的对称加密和非对称加密函数的示例代码,通过这些函数可以实现对数据的加密和解密。掌握这些函数及相关的知识,可以帮助保护敏感信息的安全。