简体   繁体   中英

Encrypt Image in Php Using AES Algorithm

I am trying to encrypt image while uploading using AES 128 bit but the text get encrypted and decrypted but i am not getting how to encrypt images before uploading. Below is the code for AES that i am using:

Code:

<?php
/**
Aes encryption
*/
class AES {

  const M_CBC = 'cbc';
  const M_CFB = 'cfb';
  const M_ECB = 'ecb';
  const M_NOFB = 'nofb';
  const M_OFB = 'ofb';
  const M_STREAM = 'stream';

  protected $key;
  protected $cipher;
  protected $data;
  protected $mode;
  protected $IV;
/**
* 
* @param type $data
* @param type $key
* @param type $blockSize
* @param type $mode
*/
  function __construct($data = null, $key = null, $blockSize = null, $mode = null) {
    $this->setData($data);
    $this->setKey($key);
    $this->setBlockSize($blockSize);
    $this->setMode($mode);
    $this->setIV("");
  }

/**
* 
* @param type $data
*/
  public function setData($data) {
    $this->data = $data;
  }

/**
* 
* @param type $key
*/
  public function setKey($key) {
    $this->key = $key;
  }

/**
* 
* @param type $blockSize
*/
  public function setBlockSize($blockSize) {
    switch ($blockSize) {
      case 128:
      $this->cipher = MCRYPT_RIJNDAEL_128;
      break;

      case 192:
      $this->cipher = MCRYPT_RIJNDAEL_192;
      break;

      case 256:
      $this->cipher = MCRYPT_RIJNDAEL_256;
      break;
    }
  }

/**
* 
* @param type $mode
*/
  public function setMode($mode) {
    switch ($mode) {
      case AES::M_CBC:
      $this->mode = MCRYPT_MODE_CBC;
      break;
      case AES::M_CFB:
      $this->mode = MCRYPT_MODE_CFB;
      break;
      case AES::M_ECB:
      $this->mode = MCRYPT_MODE_ECB;
      break;
      case AES::M_NOFB:
      $this->mode = MCRYPT_MODE_NOFB;
      break;
      case AES::M_OFB:
      $this->mode = MCRYPT_MODE_OFB;
      break;
      case AES::M_STREAM:
      $this->mode = MCRYPT_MODE_STREAM;
      break;
      default:
      $this->mode = MCRYPT_MODE_ECB;
      break;
    }
  }

/**
* 
* 
* @return boolean
*/
  public function validateParams() {
    if ($this->data != null &&
        $this->key != null &&
        $this->cipher != null) {
      return true;
    } else {
      return FALSE;
    }
  }

  public function setIV($IV) {
        $this->IV = $IV;
    }
  protected function getIV() {
      if ($this->IV == "") {
        $this->IV = mcrypt_create_iv(mcrypt_get_iv_size($this->cipher, $this->mode), MCRYPT_RAND);
      }
      return $this->IV;
  }

/**
* @return type
* @throws Exception
*/
  public function encrypt() {

    if ($this->validateParams()) {
      return trim(base64_encode(
        mcrypt_encrypt(
          $this->cipher, $this->key, $this->data, $this->mode, $this->getIV())));
    } else {
      throw new Exception('Invlid params!');
    }
  }
/**
* 
* @return type
* @throws Exception
*/
  public function decrypt() {
    if ($this->validateParams()) {
      return trim(mcrypt_decrypt(
        $this->cipher, $this->key, base64_decode($this->data), $this->mode, $this->getIV()));
    } else {
      throw new Exception('Invlid params!');
    }
  }

}
?>

<?php
include 'enc.php';


if(isset($_POST['submit']))
{
    $blockSize = 128;
    $inputKey = "My text to encrypt";



$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$fileName = $_FILES['file']['name'];
$extension = substr($fileName, strrpos($fileName, '.') + 1); // getting the info about the image to get its extension

if(in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
     echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    $aes = new AES($_FILES["file"]["tmp_name"], $inputKey, $blockSize);
    $enc = $aes->encrypt();
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
        echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
       move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $enc."jpg");
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
}
?>
<form method="post"  enctype="multipart/form-data" >

<label for="file"><span>Filename:</span></label>

<input type="file" name="file" id="file" /> 

<br />
<input type="submit" name="submit" value="Submit" />
</form>

The problem is that you don't encrypt the image, but only the filename. So you need to read the file contents from the temporary file, encrypt the contents and write the contents to the target file. The temporary file is deleted afterwards.

if (file_exists("upload/" . $_FILES["file"]["name"]))
  {
    echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
    $fileData = file_get_contents($_FILES["file"]["tmp_name"]);
    $aes = new AES($fileData, $inputKey, $blockSize);
    $encData = $aes->encrypt();
    file_put_contents("upload/" . $_FILES["file"]["name"] . "jpg", $encData);
    unlink($_FILES["file"]["tmp_name"]);
    echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "jpg";
  }

Notes:

  • The encrypted file is Base64 encoded which might not be what you want, but since you're using this AES implementation this is done consistently.
  • The unencrypted file is sent over the network (when you're not using SSL/TLS) and it is stored for a short amount of time in the temp folder in unencrypted form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM