Home > Backend Development > PHP Tutorial > How to Securely Encrypt and Decrypt Files Using AES256 in PHP?

How to Securely Encrypt and Decrypt Files Using AES256 in PHP?

Mary-Kate Olsen
Release: 2024-11-25 03:41:15
Original
931 people have browsed it

How to Securely Encrypt and Decrypt Files Using AES256 in PHP?

Encrypting / Decrypting Files with Mcrypt

Mcrypt has been deprecated and is no longer recommended for use. This article presents an alternative approach using openssl.

AES256 Encryption and Decryption

This updated implementation employs AES256 for encryption, providing a significantly higher level of security compared to Mcrypt. Below is the revised code:

class AES256Encryption
{
    public const BLOCK_SIZE = 8;
    public const IV_LENGTH = 16;
    public const CIPHER = 'AES256';

    public static function generateIv(bool $allowLessSecure = false): string
    {
        // Logic to generate a secure initialization vector
    }

    protected static function getPaddedText(string $plainText): string
    {
        // Logic to pad the plaintext to a multiple of the block size
    }

    public static function encrypt(string $plainText, string $key, string $iv): string
    {
        // Logic to encrypt the plaintext using AES256
    }

    public static function decrypt(string $encryptedText, string $key, string $iv): string
    {
        // Logic to decrypt the ciphertext using AES256
    }
}
Copy after login

Usage:

$text = 'Your plaintext here';
$key = 'Your encryption key';
$iv = AES256Encryption::generateIv();
$encryptedText = AES256Encryption::encrypt($text, $key, $iv);
$decryptedText = AES256Encryption::decrypt($encryptedText, $key, $iv);

// Print the results
echo "Original Text: $text" . PHP_EOL;
echo "Encrypted: $encryptedText" . PHP_EOL;
echo "Decrypted: $decryptedText" . PHP_EOL;
Copy after login

This code demonstrates the encryption and decryption of plaintext using AES256, ensuring secure data handling.

The above is the detailed content of How to Securely Encrypt and Decrypt Files Using AES256 in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template