Skip to content

Instantly share code, notes, and snippets.

@cythrawll
Created December 10, 2013 03:41
Show Gist options
  • Save cythrawll/7885408 to your computer and use it in GitHub Desktop.
Save cythrawll/7885408 to your computer and use it in GitHub Desktop.
early idea for easy crypther
<?php
class Crypter {
public static $cipher = MCRYPT_TWOFISH;
public $key;
public $authKey;
public function __construct($key, $authKey) {
$this->key = base64_decode($key);
$this->authKey = base64_decode($authKey);
}
public function encrypt($string) {
$ivSize = mcrypt_get_iv_size(static::$cipher, "cbc");
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$encrypt = mcrypt_encrypt(static::$cipher, $this->key, $string, "cbc", $iv);
$cipher = $encrypt.$iv;
$mac = hash_hmac("sha256", $cipher, $this->authKey, true);
return base64_encode($cipher.$mac);
}
public function decrypt($string) {
$ivSize = mcrypt_get_iv_size(static::$cipher, "cbc");
$term = base64_decode($string);
$mac = substr($term, -32);
$cipher = substr($term, 0, -32);
if(hash_hmac("sha256", $cipher, $this->authKey, true) !== $mac) {
throw new Exception("Cannot decrypt message, message is corrupted");
}
$iv = substr($cipher, $ivSize * -1);
$crypt = substr($cipher, 0, $ivSize * -1);
return mcrypt_decrypt(static::$cipher, $this->key, $crypt, "cbc", $iv);
}
public static function generateKey() {
$ivSize = mcrypt_get_iv_size(static::$cipher, "cbc");
return base64_encode(mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment