Home >Backend Development >PHP Problem >How to implement aes encryption in php
In PHP, you can use the "openssl_encrypt()" function to implement aes encryption. You only need to set the encryption method in the parameter to "AES-128-ECB". The syntax is "openssl_decrypt(encrypted plaintext,' AES-128-ECB', encryption key, data format)".
The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.
In php we use openssl_encrypt to implement encryption and openssl_decrypt to implement decryption
1: Detailed explanation of openssl_encrypt method:
openssl_encrypt($data, $method, $key, $options = 0, $iv = "", &$tag = NULL, $aad = "", $tag_length = 16)
Parameters:
1.$data: Encrypted plain text
2.$method: Encryption method: What encryption methods can be obtained through openssl_get_cipher_methods()
3.$passwd: Encryption key [password]
4.$options: Data format options (optional) [options are:]: 0, OPENSSL_RAW_DATA=1, OPENSSL_ZERO_PADDING=2, OPENSSL_NO_PADDING=3
5.$iv: Password initialization vector (optional), please note: if the method is DES-ECB, iv does not need to be filled in
6.$tag: Use AEAD password mode (GCM or CCM) when passing the referenced verification tag (optional)
7.$aad: additional verification data. (Optional)
8.$tag_length: Verify the length of tag. In GCM mode, its range is 4 to 16 (optional)
2: Detailed explanation of openssl_decrypt method
openssl_decrypt($data, $method, $password, $options = 1, $iv = "", $tag = "", $aad = "")
Parameters:
1.$ data: The encrypted message to be decrypted.
2.$method: Decryption method: What decryption methods can be obtained through openssl_get_cipher_methods()
3.$passwd: Decryption key [password]
4.$ options: Data format options (optional) [options are:] 0, OPENSSL_RAW_DATA=1, OPENSSL_ZERO_PADDING=2, OPENSSL_NO_PADDING=3
5.$iv: Secret initialization vector (optional), please note: If If method is DES−ECB, iv does not need to be filled in
6.$tag: Authentication tag in AEAD password mode (optional)
7.$aad: Additional verification data. (Optional)
3: Implement AES encryption and decryption
1: AES encryption
// 要加密的字符串 $data = 'test'; // 密钥 $key = '123456'; // 加密数据 'AES-128-ECB' 可以通过openssl_get_cipher_methods()获取 $encrypt = openssl_encrypt($data, 'AES-128-ECB', $key, 0); echo (($encrypt));
2:AES decryption
//解密字符串 $encrypt = '***'; //密钥 $key = '123456'; // 解密数据 $decrypt = openssl_decrypt($encrypt, 'AES-128-ECB', $key, 0); echo $decrypt;
According to the above, you can realize the encryption and decryption function of AES
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement aes encryption in php. For more information, please follow other related articles on the PHP Chinese website!