Skip to content

Instantly share code, notes, and snippets.

@ezimuel
Created April 26, 2018 13:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ezimuel/67fa19030c75052b0dde278a383eda1b to your computer and use it in GitHub Desktop.
Save ezimuel/67fa19030c75052b0dde278a383eda1b to your computer and use it in GitHub Desktop.
Decrypt a file in PHP form an encrypted file with OpenSSL CLI
<?php
/**
* Decrypt a file generated with the command line:
* openssl enc -aes-256-cbc -in file-to-encrypt -out encrypted-file -k password
*
* To decrypt:
* php decrypt.php encrypted-file password decrypted-file
*
* NOTE: this script has been tested with OpenSSL v.1.1, for old version
* please check if you need to use MD5 instead of SHA256 in EVP_BytesToKey()
*
* @author Enrico Zimuel (enrico@zimuel.it)
*/
if (count($argv) < 4) {
printf("Usage: %s <file_to_decrypt> <key> <decrypted_file>\n", basename(__FILE__));
exit(1);
}
$file = $argv[1];
if (!file_exists($file)) {
throw new \Exception(sprintf("The file %s does not exist!", $file));
}
$secretKey = $argv[2];
$output = $argv[3];
$data = file_get_contents($file);
$salt = mb_substr($data, 8, 8, '8bit'); // Get the salt, skipping "Salted__" fixed header string
$genKeyData = EVP_BytesToKey($salt, $secretKey);
$key = mb_substr($genKeyData, 0, 32, '8bit');
$iv = mb_substr($genKeyData, 32, 16, '8bit');
$ciphertext = mb_substr($data, 16, null, '8bit');
$result = openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
if (empty($result)) {
printf("ERROR: %s\n", openssl_error_string());
exit(1);
}
file_put_contents($output, $result);
printf("Decryption ok! The output has been stored in %s\n", $output);
function EVP_BytesToKey($salt, $password) {
$bytes = "";
$last = "";
// 32 bytes key + 16 bytes IV = 48 bytes.
while(strlen($bytes) < 48) {
$last = hash('sha256', $last . $password . $salt, true);
$bytes.= $last;
}
return $bytes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment