Home >Backend Development >PHP Tutorial >How Can I Securely Encrypt and Decrypt Files in PHP Using Modern Libraries?

How Can I Securely Encrypt and Decrypt Files in PHP Using Modern Libraries?

DDD
DDDOriginal
2024-11-19 14:55:02914browse

How Can I Securely Encrypt and Decrypt Files in PHP Using Modern Libraries?

Encrypting and Decrypting Files with Mcrypt: A Modern Approach

Introduction

Mcrypt, once a popular encryption library for PHP, has been deprecated and is no longer recommended for use. For secure and reliable file encryption, modern alternatives like OpenSSL or Sodium PHP provide robust solutions.

Encryption Function

Here's an updated encryption function using OpenSSL:

function encryptFile($fileData, $key)
{
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC'));
    $encryptedData = openssl_encrypt($fileData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($iv . $encryptedData);
}

Decryption Function

Similarly, the following decryption function utilizes the new library:

function decryptFile($encryptedData, $key)
{
    $ivSize = openssl_cipher_iv_length('AES-256-CBC');
    $iv = substr($encryptedData, 0, $ivSize);
    $encryptedData = substr($encryptedData, $ivSize);
    $decryptedData = openssl_decrypt($encryptedData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decryptedData;
}

Usage

To encrypt a file, read its contents into a variable, call the encryptFile function with the contents and the encryption key, and save the encrypted data to the output file.

For decryption, read the encrypted file's contents into a variable, call the decryptFile function with the encrypted data and the decryption key, and write the decrypted data to the output file.

Conclusion

By leveraging modern encryption libraries, you can securely encrypt and decrypt files in PHP, ensuring the confidentiality and integrity of sensitive data.

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

Statement:
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