Created
December 10, 2013 03:41
-
-
Save cythrawll/7885408 to your computer and use it in GitHub Desktop.
early idea for easy crypther
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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