<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

class CryptMCrypt extends Crypt
{
  private $algorythm;
  private $mode;

  public function __construct($algorythm = '', $mode = '', $padding = null)
  {
    $this->algorythm = $algorythm;
    $this->mode = $mode;
    parent::__construct($padding);
  }

  public static function isAvailable()
  { 
    return function_exists('mcrypt_encrypt');
  }

  protected function getModulName()
  {
    return 'mcrypt';
  }

  public function doAesEncrypt($data, $key, $iv)
  {
    $cipher = mcrypt_module_open($this->getCryptAlgorythm(), '', $this->getCryptAlgorythmMode(), '');
    mcrypt_generic_init($cipher, $key, $iv);
    $data = mcrypt_generic($cipher, $data);
    mcrypt_generic_deinit($cipher);

    return $data;
  }

  public function doAesDecrypt($data, $key, $iv)
  {
    $cipher = mcrypt_module_open($this->getCryptAlgorythm(), '', $this->getCryptAlgorythmMode(), '');

    mcrypt_generic_init($cipher, $key, $iv);

    $data = mdecrypt_generic($cipher, $data);
    mcrypt_generic_deinit($cipher);

    return $data;
  }

  public function getIvLength()
  {
    $cipher = mcrypt_module_open($this->getCryptAlgorythm(), '', $this->getCryptAlgorythmMode(), '');
    $size = mcrypt_enc_get_iv_size($cipher);
    mcrypt_module_close($cipher);

    return $size;
  }

  private function getCryptAlgorythm()
  {
    if (trim($this->algorythm) == '') {
      return MCRYPT_RIJNDAEL_128;
    } else {
      return $this->algorythm;
    }
  }

  private function getCryptAlgorythmMode()
  {
    if (trim($this->mode) == '') {
      return 'cbc';
    } else {
      return $this->mode;
    }
  }
}