Home > Article > Backend Development > How to encrypt and decrypt data using PHP built-in functions?
Use PHP built-in functions for encryption and decryption: Encryption: Use the openssl_encrypt() function, specifying the algorithm (such as AES-256-cbc) and passphrase to encrypt the data. Decryption: Use the openssl_decrypt() function to decrypt the encrypted data using the same algorithm and passphrase. Hashing: Use the hash() function to create an irreversible hash value used to verify data integrity (such as SHA256).
Introduction
PHP provides powerful Built-in functions are used to encrypt and decrypt data, ensuring the security of sensitive information. This article will guide you on how to use these functions for encryption and decryption operations, and provide practical examples.
Encryption
<?php $plaintext = "My secret message"; $encrypted_text = openssl_encrypt($plaintext, 'aes-256-cbc', 'secret_passphrase'); ?>
This code will encrypt the plain text message using the AES-256 encryption algorithm and a secret passphrase and store it in $encrypted_text
in variables.
Decryption
<?php $decrypted_text = openssl_decrypt($encrypted_text, 'aes-256-cbc', 'secret_passphrase'); ?>
Using the same encryption algorithm and secret passphrase, this code will decrypt the encrypted text and store it in the $decrypted_text
variable.
Hash
For irreversible encryption operations, PHP provides a hash function:
<?php $hash = hash('sha256', 'My secret message'); ?>
will return a unique and irreversible hash value , can be used to verify data integrity.
Practical Case
In the following scenarios, using encryption and decryption functions can improve the security of the application:
Conclusion
PHP’s built-in encryption and decryption functions provide powerful tools for data security. By using these functions, you can ensure the confidentiality and integrity of sensitive information.
The above is the detailed content of How to encrypt and decrypt data using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!