src/Helper/FileCrypt.php line 33

Open in your IDE?
  1. <?php
  2. namespace App\Helper;
  3. class FileCrypt
  4. {
  5.     public function encrypt($oldpath, $directory, $file, $key) {
  6.         try {
  7.             $content = file_get_contents($oldpath);
  8.             $cryptedContent = $this->encodeThis($content, 'e', $key);
  9.             $createdfile = fopen($directory."/".$file, "w") or die("Impossible de créer le fichier !");
  10.             fwrite($createdfile, $cryptedContent);
  11.             fclose($createdfile);
  12.             return true;
  13.         } catch (Exception $e) {
  14.             return false;
  15.         }
  16.     }
  17.     
  18.     public function decrypt($filePath, $document) {
  19.         try {
  20.             $content = file_get_contents($filePath);
  21.             $decryptedContent = $this->encodeThis($content, 'd', $document->getOvi());
  22.             return $decryptedContent;
  23.         } catch (Exception $e) {
  24.             return false;
  25.         }
  26.     }
  27.     public function encodeThis( $string, $action = 'e', $randkey ) {
  28.         $secret_key = $randkey;
  29.         $secret_iv = $randkey;
  30.         $output = false;
  31.         $encrypt_method = "AES-256-CBC";
  32.         $key = hash( 'sha256', $secret_key );
  33.         $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
  34.         if( $action == 'e' ) {
  35.             $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
  36.         }
  37.         else if( $action == 'd' ){
  38.             $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
  39.         }
  40.         return $output;
  41.     }
  42. }