How to encrypt and decrypt data in php?
My code so far is:-
function encrypter($plaintext)
{
$plaintext = strtolower($plaintext);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$plaintext,MCRYPT_MODE_ECB);
return trim(base64_encode($crypttext));
}
function decrypter($crypttext)
{
$crypttext = base64_decode($crypttext);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);
return trim($crypttext);
}
$test = "abc#gmail.com";
echo encrypter(test);
Output is
iLmUJHKPjPmA9vY0jfQ51qGpLPWC/5bTYWFDOj7Hr08=
echo decrypter(test);
Output is
��-
In your decrypter() function, you return the wrong data.
You should return $plaintext instead of $crypttext:
function decrypter($crypttext)
{
$crypttext = base64_decode($crypttext);
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256,FLENCKEY,$crypttext,MCRYPT_MODE_ECB);
//return trim($crypttext);
return trim($plaintext);
}
The other code samples on this page (including the question) are not secure.
To be secure:
Don't use mcrypt.
Use authenticated encryption.
Never use ECB mode (a.k.a. MCRYPT_MODE_ECB).
See this answer for secure encryption in PHP.
This is what I use. Super simple.
function encrypt_decrypt($action, $string) {
$output = false;
$key = '$b#bl2I#?%%4K*mC6r273~8l3|6#>D';
$iv = md5(md5($key));
if( $action == 'encrypt' ) {
$output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
$output = base64_encode($output);
}
else if( $action == 'decrypt' ){
$output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
$output = rtrim($output, "");
}
return $output;
}
You can change $key to whatever you want, or leave it. (this is not my key, btw)
encrypt_decrypt('encrypt', $str) to encrypt
encrypt_decrypt('decrypt', $str) to decrypt
Inside the decrypter function, change the
return trim($crypttext);
to
return trim($plaintext);
But looking at your function, I am not quite sure whether it will return exactly the same string, because of the strtolower function. You can't just do a strtoupper function as the original text may not be all in capital letters.
Warning
mcrypt_encrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
Use openssl_encrypt instead.
Related
I found a tutorial online on how to encrypt strings in php but when I call the function and try echo the processed data I'm getting 500 internal error. Here is my code below.
<?php
$iv_to_pass_to_decryption = 'mysecretpass';
function encrypt($text, $key)
{
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND);
$iv_to_pass_to_decryption = base64_encode($iv);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
}
function decrypt($text, $key, $iv)
{
$text = base64_decode($text);
$iv = base64_decode($iv);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
}
$txt = "hello";
$mykey = "mysecretkey";
$somedata = encrypt($txt, $mykey);
echo $somedata;
?>
The first problem is, you missed a ) in line 8.
The second problem is mcrypt_decrypt()function is deprecated.
The third problem is mcrypt_encrypt(): Key of size 11 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported. The 'mysecretkey' key is wrong.
I can recommend use the crypt() function: http://php.net/manual/en/function.crypt.php
When validating passwords, a string comparison function that isn't
vulnerable to timing attacks should be used to compare the output of
crypt() to the previously known hash. PHP 5.6 onwards provides
hash_equals() for this purpose.
use below code hope it will help you
$iv_to_pass_to_decryption = 'mysecretpass';
function encrypt($text, $key)
{
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND);
$iv_to_pass_to_decryption = base64_encode($iv);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv));
}
function decrypt($text, $key, $iv)
{
$text = base64_decode($text);
$iv = base64_decode($iv);
return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
}
$txt = "hello";
$mykey = "mysecretkey12345";
$somedata = encrypt($txt, $mykey);
echo $somedata;
Hi and good day to all members, admin and to everyone. I would like to ask a question that has a connection from my previous post which can be seen here entitled Crypto-Js different output from mcrypt Upon chage of data to encrypt. Now my question is I made another php function that will eventually call this function stated in the link. See below the basic php function I created.
function login($word,$word2)
{
$word = mcrypts_encrypt($word);
$word2 = mcrypts_encrypt($word2);
return $word;
return $word2;
}
Now my question is this, I have tried placing the $word and the $word 2 with real data such as CROW and Blader but It only echoes the encrypted word of CROW ($word) and not Blader ($w0rd2).
For reference purpose I will also include the script for the encrypt.
MCRYPT_ENCRYPT
function mcrypts_encrypt($encrypted)
{
//Padding 6/25/2014
$pad = 16 - (strlen($encrypted) % 16);
$encrypted = $encrypted . str_repeat(chr($pad), $pad);
//Encrypt//Decode
$iv = base64_decode('AAAAAAAAAAAAAAAAAAAAAA==');
$key = base64_decode('ITU2NjNhI0tOc2FmZExOTQ==');
$plaintext = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv );
//Return encrypted Data
return base64_encode($plaintext);
}
Thanks for the help in advance.
You can only call return from a function once, at that point, the flow of code is returned back to the caller.
To pass multiple values back to the caller, return an array containing both of the values, e.g.
function login($word,$word2)
{
$word = mcrypts_encrypt($word);
$word2 = mcrypts_encrypt($word2);
return array($word, $word2);
}
and use as this;
$encrypted = login('first-word', 'second-word');
echo $encrypted[0]; // the first word, encrypted
echo $encrypted[1]; // the second word, encrypted
function login($word,$word2)
{
$word = mcrypts_encrypt($word);
$word2 = mcrypts_encrypt($word2);
$returnArray["user"] = $word;
$returnArray["pass"] = $word2;
return $returnArray;
}
function call
$loginValues = login('CROW','Blader');
extract($loginValues);
print $user; // prints $word
print $pass; // prints $word2
This works
<?php
function login($word,$word2)
{
$word = mcrypts_encrypt($word);
$word2 = mcrypts_encrypt($word2);
return array($word, $word2);
}
function mcrypts_encrypt($encrypted)
{
//Padding 6/25/2014
$pad = 16 - (strlen($encrypted) % 16);
$encrypted = $encrypted . str_repeat(chr($pad), $pad);
//Encrypt//Decode
$iv = base64_decode('AAAAAAAAAAAAAAAAAAAAAA==');
$key = base64_decode('ITU2NjNhI0tOc2FmZExOTQ==');
$plaintext = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv );
//Return encrypted Data
return base64_encode($plaintext);
}
var_dump(login("test1", "test2"));
?>
outputs:
array(2) {
[0]=>
string(24) "eeyZfxyUnMykJ23fMamEBQ=="
[1]=>
string(24) "0egb4dfuXbgFg7GzuuBZcQ=="
}
I need two functions/methods, one to encode, one to decode. This is not for storing passwords. Each user will have a specific key/salt to encode the data.
This is how I would like it to work:
function encode($str, $key) {
// something fancy
}
function decode($str, $key) {
// something fancy
}
$key = $logged_in_user->get_key();
$plain = 'abc abc 123 123';
$encoded_data = encode($plain, $key);
// some_fancy_encrypted_data_that_is_really_cooooool
$decoded_data = decode($encoded_data, $key);
// abc abc 123 123
Another thing is that every time I use this function it needs to return the same thing every time I use the encode function with the same user key.
How would I do this??
$myVarIWantToEncodeAndDecode
Define key (salt, broth etc..): $key = "#&$sdfdfs789fs7d";
To encode:
$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $myVarIWantToEncodeAndDecode, MCRYPT_MODE_CBC, md5(md5($key))));
To decode:
$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encoded), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
Note: mcrypt_decrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.
Use openssl_encrypt instead of mcrypt_encrypt
mcrypt_encrypt DEPRECATED as of PHP 7.1.0 and REMOVED as of PHP 7.2.0.
So, Try this..
function encrypt_decrypt($string, $action = 'encrypt')
{
$encrypt_method = "AES-256-CBC";
$secret_key = 'AA74CDCC2BBRT935136HH7B63C27'; // user define private key
$secret_iv = '5fgf5HJ5g27'; // user define secret key
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 16); // sha256 is hash_hmac_algo
if ($action == 'encrypt') {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
echo "Your Encrypted password is = ". $pwd = encrypt_decrypt('spaceo', 'encrypt');
echo "Your Decrypted password is = ". encrypt_decrypt($pwd, 'decrypt');
I am trying to mcrypt some data using a class I created (methods below). This is how you mcrypt data then using pack, then you can use unpack to get the data back.
$packed = $server->cache->pack("packed", array(123,123,123), "Password");
if(!$packed){
echo "Could not encrypt data\n";
}
$server->cache->unpack("packed", "Password");
when I pack it, I do a var_dump on the json_encode() data, and get this:
string(13) "[123,123,123]"
When I unpack it, I do a var_dump on the mcrypt_decode() string, and get this:
string(32) "[123,123,123]"
Why are the lengths different? When I do a json_decode() on the mcrypt_decode() string, I get null back, and this is the reason. If I trim the data it works, but I shouldn't have to trim it.
Here are the methods:
<?php
public function put($key, $value, $life = 0)
{
$this->cache[$key] = $value;
$life = (int)$life;
if($life > 0)
{
$life = strtotime("now + $life seconds");
}
$this->life[$key] = $life;
}
public function get($key)
{
return $this->cache[$key];
}
public function pack($key, $value, $secret, $life = 0)
{
if(!function_exists("mcrypt_encrypt"))
{
$this->put($key, $value, $life);
return false;
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$value = json_encode($value);
var_dump($value);
$cryptdata = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret, $value, MCRYPT_MODE_ECB, $iv);
$this->put($key, $cryptdata, $life);
return true;
}
public function unpack($key, $secret)
{
if(!function_exists("mcrypt_decrypt"))
{
return json_decode($this->get($key), true);
}
$cryptdata = $this->get($key);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret, $cryptdata, MCRYPT_MODE_ECB, $iv);
//$data = json_decode($data, true);
var_dump($data);
}
When using a block cipher mode like ECB (you shouldn't be using that one btw), MCrypt will NUL-pad the data, so that its length is dividable by the encryption algorithm's block size.
If you must know, for Rijndael-256 the block size is 256 bits or 32 bytes.
Considering that you're encrypting JSON data, you can just rtrim() the data and not worry about it. There's no way around that unless you switch to a counter mode like CTR.
I have no idea what I'm doing wrong. I just need to be able to encrypt and decrypt without getting weird characters or warnings. It says I'm supposed to be using an IV of length 16 and that I'm using a length of 9 but "0123456789abcdef" is 16 characters.
Warning: mcrypt_generic_init() [function.mcrypt-generic-init]: Iv size incorrect; supplied length: 9, needed: 16 in /home/mcondiff/public_html/projects/enc/enc.php on line 10
See http://www.teamconcept.org/projects/enc/enc.php
I'm lost, confused, a little lightheaded. Here do I go from here? I have to use this encryption and get it working for a project.
<?php
class enc
{
function encrypt($str, $key) {
$key = $this->hex2bin($key);
$td = mcrypt_module_open("rijndael-128", "", "cbc", "fedcba9876543210");
mcrypt_generic_init($td, $key, CIPHER_IV);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}
function decrypt($code, $key) {
$key = $this->hex2bin($key);
$code = $this->hex2bin($code);
$td = mcrypt_module_open("rijndael-128", "", "cbc", "fedcba9876543210");
mcrypt_generic_init($td, $key, CIPHER_IV);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return utf8_encode(trim($decrypted));
}
function hex2bin($hexdata) {
$bindata = "";
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
$theEncryption = new enc();
$user = "John Doe";
$email = "john#example.com";
$user = $theEncryption->encrypt($user, "0123456789abcdef");
$email = $theEncryption->encrypt($email, "0123456789abcdef");
echo 'User: '.$user;
echo 'Email: '.$email;
?>
Can somone point me in the right direction or point out what i'm doing wrong?
Thanks
Mike
CIPHER_IV is probably an undefined constant. PHP raises a "Use of undefined constant" notice and then uses the "constant" as string. The string "CIPHER_IV" is 9 characters long.
In your php file, do a print of CIPHER_IV and see what it contains.
See http://us2.php.net/mcrypt_generic_init for the specifics
You've probably copy-pasted the code from a blog: googling mcrypt_generic_init CIPHER_IV only gives this post and a blog ;)
The IV is a parameter that you need to specify to the function, not a constant that the first blogger put in misinterpreting the second blogger's article.
At http://propaso.com/blog/?cat=6, they declare these:
$secret_key = "01234567890abcde";
$iv = "fedcba9876543210";
and then do:
mcrypt_generic_init($td, $secret_key, $iv);
Simply declare your IV to be something, then use it.