note 78531 deleted from function.mcrypt-encrypt by derick
| From: | derick@php.net | Date: | Tue, 18 Aug 2015 15:56:52 +0000 |
| Subject: | note 78531 deleted from function.mcrypt-encrypt by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-203379@lists.php.net to get a copy of this message | ||
Note Submitter: dylan at wedefy dot com
----
I wasn't too impressed with the suggested functions/classes for using mcrypt, so I wrote my own
class. The encypted output is base64 encoded so it can be used in URLs, emails, etc.
MCRYPT_RIJNDAEL_256 is probably too secure for most uses, using a less secure algorithm should mean
that the encryption will be faster and the encrypted output shorter (make sure to update iv_size in
mcrypt_create_iv() and key length to match the new algorithm). If you are going to use only 1
passphrase, you should define it inside __construct($this->securekey) instead of when creating
the object. Keep the class in a separate include file which is only readable by your webserver (or
whatever needs it) for added security.
<?php
class Cipher {
private $securekey, $iv;
function __construct($textkey) {
$this->securekey = hash('sha256',$textkey,TRUE);
$this->iv = mcrypt_create_iv(32);
}
function encrypt($input) {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input,
MCRYPT_MODE_ECB, $this->iv));
}
function decrypt($input) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input),
MCRYPT_MODE_ECB, $this->iv));
}
}
$cipher = new Cipher('secret passphrase');
$encryptedtext = $cipher->encrypt("hide me");
echo "->encrypt = $encryptedtext<br />";
$decryptedtext = $cipher->decrypt($encryptedtext);
echo "->decrypt = $decryptedtext<br />";
var_dump($cipher);
?>