Home >Backend Development >PHP Tutorial >How to Securely Encrypt and Decrypt Files Using OpenSSL and a Custom PHP Class?
How to Encrypt and Decrypt Files Using Mcrypt
Mcrypt, a popular encryption library, has been discontinued and is no longer recommended for use. For this reason, we will explore an alternative encryption technique using the OpenSSL extension.
Creating a Custom Encryption Class
To encapsulate the encryption process, we define a custom class, AES256Encryption, which leverages OpenSSL's AES-256 algorithm.
class AES256Encryption { const BLOCK_SIZE = 8; const IV_LENGTH = 16; const CIPHER = 'AES256'; //... Encryption and Decryption Methods ... }
Usage
$text = 'Plain text to be encrypted'; $key = 'Encryption key'; $iv = AES256Encryption::generateIv(); // Generates a random initialization vector (IV) $encryptedText = AES256Encryption::encrypt($text, $key, $iv); // Encrypts the text $decryptedText = AES256Encryption::decrypt($encryptedText, $key, $iv); // Decrypts the encrypted text
Sample Output
Original Text: Plain text to be encrypted Encrypted: Encrypted ciphertext Decrypted: Plain text to be encrypted
Other Considerations
This updated approach using OpenSSL provides a secure and reliable method for encrypting and decrypting files and data using the latest encryption standards.
The above is the detailed content of How to Securely Encrypt and Decrypt Files Using OpenSSL and a Custom PHP Class?. For more information, please follow other related articles on the PHP Chinese website!