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 加密和其他方法的所有選項此處

Author: 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