HP には、PHP のメソッドを使用してAES
文字列を暗号化および復号化するための拡張機能が組み込まれています。
openssl_encrypt()
文字列の暗号化と復号化に使用される関数openssl_decrypt()
。
[PHP の Open SSL 関数を使用して文字列を暗号化および復号化する]
openssl_encrypt()
openssl_decrypt()
必須パラメータとオプションのパラメータのセットを受け取ります。パラメータに関する情報を次の表に示します。
範囲 | 説明する |
---|---|
data |
プレーンテキスト/文字列 |
cipher_algo |
私たちの場合、暗号化メソッドは、AES |
passphrase |
パスフレーズが制限より短い場合は、暗黙のうちに null 文字が埋め込まれ、長い場合は切り捨てられます。 |
options |
フラグのビット単位の分離。OPENSSL_RAW_DATA そしてOPENSSL_ZERO_PADDING 。 |
iv |
初期化ベクトル、空ではありません |
tag |
認証タグCGM またはCCM |
aad |
追加の認証データ。 |
tag_length |
認証タグの長さは 4 ~ 16 です。 |
openssl_encrypt()
を使用する場合は、とopenssl_decrypt()
を除く、上記のすべてのパラメータを受け取ります。aad
tag_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-cbc
、aes-192-cfb
、 などのさまざまなオプションがありますaes-256-cbc
。
AES 暗号化およびその他の方法のすべてのオプションをここで参照してください。