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

PHP中使用的加密算法及对应的函数

发布时间:2023-06-14 16:37:25

在PHP中,有多种加密算法可供使用,包括对称加密算法和非对称加密算法。对称加密算法使用相同密钥对数据进行加密和解密,而非对称加密算法使用公钥和私钥进行加密和解密。下面是常用的加密算法及对应的函数:

1. MD5加密算法:使用md5()函数进行加密,如下:

$hash = md5('hello world');
echo $hash;

2. SHA-1加密算法:使用sha1()函数进行加密,如下:

$hash = sha1('hello world');
echo $hash;

3. AES加密算法:使用openssl_encrypt()和openssl_decrypt()函数进行加密和解密,如下:

$key = 'secretkey';
$data = 'hello world';
$cipher = 'AES-256-CBC';

$encrypted = openssl_encrypt($data, $cipher, $key, 0, $key);
echo $encrypted;

$decrypted = openssl_decrypt($encrypted, $cipher, $key, 0, $key);
echo $decrypted;

4. RSA加密算法:使用openssl_pkey_new()、openssl_private_encrypt()和openssl_public_decrypt()函数进行加密和解密,如下:

// 生成公钥和私钥
$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$publicKey = openssl_pkey_get_details($res);
$publicKey = $publicKey['key'];

// 加密数据
$data = 'hello world';
openssl_private_encrypt($data, $encryptedData, $privateKey);
echo $encryptedData;

// 解密数据
openssl_public_decrypt($encryptedData, $decryptedData, $publicKey);
echo $decryptedData;

总之,PHP支持许多加密算法,可以根据实际需要选择最合适的算法。