PHP AES 加密解密

Sheeraz Gul 2022年5月13日
PHP AES 加密解密

PHP 有一个使用 PHP 的 AES 方法加密和解密字符串的内置扩展。

函数 openssl_encrypt() 用于加密字符串,openssl_decrypt() 用于解密字符串。

在 PHP 中使用 Open SSL 函数加密和解密字符串

openssl_encrypt()openssl_decrypt() 采用一组强制和可选参数,有关参数的信息如下表所示:

范围 描述
data 纯文本/字符串
cipher_algo 密码方法,在我们的例子中,AES
passphrase 如果密码短语短于限制,则会用空字符静默填充,如果长则截断。
options 标志的按位分离。OPENSSL_RAW_DATAOPENSSL_ZERO_PADDING
iv 初始化向量,非空
tag 身份验证标签 CGMCCM
aad 额外的身份验证数据。
tag_length 身份验证标签的长度在 4 到 16 之间

openssl_encrypt() 采用上述所有参数,并在使用 openssl_decrypt() 时排除 aadtag_length

<?php
//Encryption
$original_string = "Hello! This is delftstack";  // Plain text/String
$cipher_algo = "AES-128-CTR"; //The cipher method, in our case, AES 
$iv_length = openssl_cipher_iv_length($cipher_algo); //The length of the initialization vector
$option = 0; //Bitwise disjunction of flags
$encrypt_iv = '8746376827619797'; //Initialization vector, non-null
$encrypt_key = "Delftstack!"; // The encryption key
// Use openssl_encrypt() encrypt the given string
$encrypted_string = openssl_encrypt($original_string, $cipher_algo,
			$encrypt_key, $option, $encrypt_iv);

//Decryption
$decrypt_iv = '8746376827619797'; //Initialization vector, non-null
$decrypt_key = "Delftstack!"; // The encryption key
// Use openssl_decrypt() to decrypt the string
$decrypted_string=openssl_decrypt ($encrypted_string, $cipher_algo,
		$decrypt_key, $option, $decrypt_iv);

//Display Strings
echo "The Original String is: <br>" . $original_string. "<br><br>" ;
echo "The Encrypted String is: <br>" . $encrypted_string . "<br><br>";
echo "The Decrypted String is: <br>" . $decrypted_string;
?>

上面的代码首先使用 AES 方法对字符串进行加密,然后对其进行解密。

输出:

The Original String is:
Hello! This is delftstack

The Encrypted String is:
21tZwb2Wrw2gPGid29Bfy7TacU1bEmCbaw==

The Decrypted String is:
Hello! This is delftstack

AES 根据方法和位数具有不同的 cipher_algorithams,例如 aes-128-cbcaes-192-cfbaes-256-cbc

查看 AES 加密和其他方法的所有选项此处

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook