Home  >  Article  >  Backend Development  >  How Can I Encrypt and Decrypt Files Using PHP\'s mcrypt and the openssl Alternative?

How Can I Encrypt and Decrypt Files Using PHP\'s mcrypt and the openssl Alternative?

Linda Hamilton
Linda HamiltonOriginal
2024-11-20 11:57:16502browse

How Can I Encrypt and Decrypt Files Using PHP's mcrypt and the openssl Alternative?

Encrypting and Decrypting Files with PHP's mcrypt

Encrypting and decrypting files can enhance data security and protect sensitive information. mcrypt offers a convenient library for implementing encryption and decryption operations in PHP. However, since mcrypt is no longer actively maintained, it's essential to consider alternative options for encryption tasks.

In this article, we'll explore the use of mcrypt to encrypt and decrypt files. We'll also provide an updated example utilizing openssl, a recommended alternative to mcrypt.

Encrypting a File with mcrypt:

</p>
<pre class="brush:php;toolbar:false">function encryptFile() {
    global $cryptastic;
    $pass = PGPPASS;
    $salt = PGPSALT;
    $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key.");

    if ($handle = opendir(PATH.'/ftpd')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." &amp;&amp; $file != "..") {
                $newfile = PATH.'/encrypted/'.$file.'.txt';
                $msg = file_get_contents(PATH.'/ftpd/'.$file);
                $encrypted = $cryptastic->encrypt($msg, $key) or die("Failed to complete encryption.");
                $nfile = fopen($newfile, 'w');
                fwrite($nfile, $encrypted);
                fclose($nfile);
                unlink(PATH.'/ftpd/'.$file);

            }
        }
        closedir($handle);
    }
}

Decrypting a File with mcrypt:

</p>
<pre class="brush:php;toolbar:false">function inFTP() {
    global $cryptastic;
    $pass = PGPPASS;
    $salt = PGPSALT;
    $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key.");

    if ($handle = opendir(PATH.'/encrypted')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." &amp;&amp; $file != "..") {
                $newfile = PATH.'/decrypted/'.$file;
                $msg = PATH.'/encrypted/'.$file;
                $decrypted = $cryptastic->decrypt($msg, $key) or die("Failed to complete decryption.");
                $nfile = fopen($newfile, 'w');
                fwrite($nfile, $decrypted);
                fclose($nfile);
                //unlink(PATH.'/encrypted/'.$file);

            }
        }
        closedir($handle);
    }
}

Alternative Option: Encrypting and Decrypting with openssl

<br>class AES256Encryption<br>{</p>
<pre class="brush:php;toolbar:false">public const BLOCK_SIZE = 8;
public const IV_LENGTH = 16;
public const CIPHER = 'AES256';

public static function generateIv(bool $allowLessSecure = false): string
{
    $success = false;
    $random = openssl_random_pseudo_bytes(openssl_cipher_iv_length(static::CIPHER));
    if (!$success) {
        if (function_exists('sodium_randombytes_random16')) {
            $random = sodium_randombytes_random16();
        } else {
            try {
                $random = random_bytes(static::IV_LENGTH);
            }
            catch (Exception $e) {
                if ($allowLessSecure) {
                    $permitted_chars = implode(
                        '',
                        array_merge(
                            range('A', 'z'),
                            range(0, 9),
                            str_split('~!@#$%&amp;*()-=+{};:"<>,.?/\'')
                        )
                    );
                    $random = '';
                    for ($i = 0; $i < static::IV_LENGTH; $i++) {
                        $random .= $permitted_chars[mt_rand(0, (static::IV_LENGTH) - 1)];
                    }
                }
                else {
                    throw new RuntimeException('Unable to generate initialization vector (IV)');
                }
            }
        }
    }
    return $random;
}

protected static function getPaddedText(string $plainText): string
{
    $stringLength = strlen($plainText);
    if ($stringLength % static::BLOCK_SIZE) {
        $plainText = str_pad($plainText, $stringLength + static::BLOCK_SIZE - $stringLength % static::BLOCK_SIZE, "<🎝🎝🎝>");
    }
    return $plainText;
}

public static function encrypt(string $plainText, string $key, string $iv): string
{
    $plainText = static::getPaddedText($plainText);
    return base64_encode(openssl_encrypt($plainText, static::CIPHER, $key, OPENSSL_RAW_DATA, $iv));
}

public static function decrypt(string $encryptedText, string $key, string $iv): string
{
    return openssl_decrypt(base64_decode($encryptedText), static::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
}

}

$text = '8SViI0Gz4r-p7A15YxkwjOBFuW*@NTtbm{U]D&E=~6yLM adX'P;h3$,KJ%/eo>}$key = 'secretkey';
$iv = AES256Encryption::generateIv();
$encryptedText = AES256Encryption::encrypt($text, $key, $iv);
$decryptedText = AES256Encryption::decrypt($encryptedText, $key, $iv);

printf('Original Text: %s%s', $text, PHP_EOL);
printf('Encrypted: %s%s', $encryptedText, PHP_EOL);
printf('Decrypted: %s%s', $decryptedText, PHP_EOL);

The above is the detailed content of How Can I Encrypt and Decrypt Files Using PHP\'s mcrypt and the openssl Alternative?. 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