<?php
namespace App\Helper;
class FileCrypt
{
public function encrypt($oldpath, $directory, $file, $key) {
try {
$content = file_get_contents($oldpath);
$cryptedContent = $this->encodeThis($content, 'e', $key);
$createdfile = fopen($directory."/".$file, "w") or die("Impossible de créer le fichier !");
fwrite($createdfile, $cryptedContent);
fclose($createdfile);
return true;
} catch (Exception $e) {
return false;
}
}
public function decrypt($filePath, $document) {
try {
$content = file_get_contents($filePath);
$decryptedContent = $this->encodeThis($content, 'd', $document->getOvi());
return $decryptedContent;
} catch (Exception $e) {
return false;
}
}
public function encodeThis( $string, $action = 'e', $randkey ) {
$secret_key = $randkey;
$secret_iv = $randkey;
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
}