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
Release: 2024-11-19 14:55:02
Original
874 people have browsed it

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);
}
Copy after login

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;
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template