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.
Related
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 have an issue using mcrypt to encrypt a file on filesystem to e.g. store it into Mysql database. I have reduced the issue to the following lines of code:
<?php
$key = vzc_generateKey();
$file_content = file_get_contents("test.pdf"); // Fails
$file_content = file_get_contents("test2.docx"); // Fails
//$file_content = "12323"; // Works great
$hash_start = md5($file_content);
$encrypt = vzc_encryptV3($file_content, $key);
$decrypt = vzc_decryptV3($encrypt, $key);
$hash_end = md5($decrypt);
echo ($hash_end == $hash_start)."##";
function vzc_generateKey()
{
$cstrong = false;
while ($cstrong == false)
{
$bytes = openssl_random_pseudo_bytes(16, $cstrong);
}
return bin2hex($bytes);
}
function vzc_decryptV3($crypt,$key) {
$content = base64_decode($crypt['crypt']);
$iv = $crypt['iv'];
$rijndael = 'rijndael-256';
$cp = mcrypt_module_open($rijndael, '', 'ofb', '');
$ks = mcrypt_enc_get_key_size($cp);
$key = substr(md5($key), 0, $ks);
mcrypt_generic_init($cp, $key, $iv);
$decrypted = mdecrypt_generic($cp, $content);
mcrypt_generic_deinit($cp);
mcrypt_module_close($cp);
return trim(base64_decode($decrypted));
}
function vzc_encryptV3($file_content,$key) {
$content = base64_encode($file_content);
$rijndael = 'rijndael-256';
$cp = mcrypt_module_open($rijndael, '', 'ofb', '');
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cp), MCRYPT_RAND);
else
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($cp), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($cp);
$key = substr(md5($key), 0, $ks);
mcrypt_generic_init($cp, $key, $iv);
$encrypted = mcrypt_generic($cp, $content);
$returnvalue = array("crypt"=>trim(base64_encode($encrypted)), "iv"=>$iv);
mcrypt_generic_deinit($cp);
mcrypt_module_close($cp);
return $returnvalue;
}
?>
Using the String "12323" everything works fine, both Hashes do equal. But those two test files (one pdf and one docx) fail. It seems that the decryption returns different values then the origin data.
What can I do to solve this issue?
Thank you very much in advance for any tip you can provide.
It is probably the fact that the files are not exactly n * blocksize long. This leads the algorithm to pad the end of the file with '\0' and this changes the content of the file when you do the md5 calculation.
One way around this is to strip the padding off of the last block, if you can reliably find the end of the file.
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.
This question already has answers here:
How to encrypt/decrypt data in php?
(6 answers)
Closed 9 years ago.
How to Encrypt password in PHP, i am using below code to insert data into database using PHP code and i am able to store new member data but now i just want to encrypt user password..
PHP Script::
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("allah);
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
/*** Insert ***/
$strSQL = "INSERT INTO member (Password,Name)
VALUES (
'".$strPassword."',
'".$strName."',
)
";
$objQuery = mysql_query($strSQL);
if(!$objQuery)
{
$arr['StatusID'] = "0";
$arr['Message'] = "Cannot save data!";
}
else
{
$arr['StatusID'] = "1";
$arr['Message'] = "Register Successfully!";
}
mysql_close($objConnect);
echo json_encode($arr);
?>
You can make use of crypt(); in php. It supports multiple hash types.
http://php.net/manual/en/function.crypt.php
Use prepared statements while doing a db query. (PDO or mysqli)
md5 is not safe anymore, sha should be used from now on. Take a look at http://php.net/manual/en/function.hash.php and use with sha256 or sha512
I believe that your question is very basic method of handling passwords to store in database.
There are many views on this if you might have googled already. However these two links might be helpful .
Check this link for knowing all methods available. You need not to follow article but it gives all possible ways of password management.
another this question!
i am using this class for encrypt.
http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php
Create a php file named MCrypt.php
<?php
class MCrypt
{
private $iv = 'fedcba9876543210'; #Same as in JAVA
private $key = '0123456789abcdef'; #Same as in JAVA
function __construct()
{
}
function encrypt($str) {
//$key = $this->hex2bin($key);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return bin2hex($encrypted);
}
function decrypt($code) {
//$key = $this->hex2bin($key);
$code = $this->hex2bin($code);
$iv = $this->iv;
$td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata) {
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
?>
and include thi php file to where you use encrypt
include(MCrypt.php);
and then use
$mcrypt = new MCrypt();
#Encrypt
$encrypted = $mcrypt->encrypt("Text to encrypt");
one last thing to add don't forget to change
$iv = 'fedcba9876543210';
$key = '0123456789abcdef';
must be 16 characters
use mysql encription ,
AES_DECRYPT()
AES_ENCRYPT()
for AES_ENCRYPT()
SELECT AES_ENCRYPT('mytext', 'mykeystring');
for AES_DECRYPT
SELECT AES_DECRYPT(AES_ENCRYPT('mytext','mykeystring'),
'mykeystring');
I have the following c# code that generates keys:
public static byte[] Encrypt(byte[] plainData, string salt)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(salt);
DES.IV = ASCIIEncoding.ASCII.GetBytes(salt);
ICryptoTransform desencrypt = DES.CreateEncryptor();
byte[] encryptedData = desencrypt.TransformFinalBlock(plainData, 0, plainData.Length);
return encryptedData;
}
private string GetEncryptedKey(string key)
{
return BitConverter.ToString(KeyGeneratorForm.Encrypt(ASCIIEncoding.ASCII.GetBytes(key), "abcdefgh")).Replace("-", "");
}
I'm trying to perform the same thing in PHP:
function get_encrypted_key($key){
$salt = "abcdefgh";
return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}
However, there is a small discrepency in the results, as the last 16 chars are always different:
With key "Benjamin Franklin":
C# : 0B3C6E5DF5D747FB3C50DE952FECE3999768F35B890BC391
PHP: 0B3C6E5DF5D747FB3C50DE952FECE3993A881F9AF348C64D
With key "President Franklin D Roosevelt":
C# : C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB32A86FABCEA5711E1
PHP: C119B50A5A7F8C905A86A43F5694B4D7DD1E8D0577F1CEB37ACBE60BB1D21F3F
I've also tried to perform the padding transform to my key using the following code:
function get_encrypted_key($key){
$salt = "abcdefgh";
$extra = 8 - (strlen($key) % 8);
if($extra > 0) {
for($i = 0; $i < $extra; $i++) {
$key.= "\0";
}
}
return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}
But I end up with the same results as without padding.
If you have any clue as to what's going on, I'd be glad to hear about it! :)
Thanks
You mentioned trying a "classic" padding snippet. The following quick adaptation of the snippet posted on the mcrypt_encrypt documentation gives the same results you were getting from C#.
PKCS #7 (the default padding scheme used by C#'s SymmetricAlgorithm) pads with bytes where each padding byte's value is the same as the number of bytes of padding, not with zero bytes.
function get_encrypted_key($key)
{
$salt = 'abcdefgh';
$block = mcrypt_get_block_size('des', 'cbc');
$pad = $block - (strlen($key) % $block);
$key .= str_repeat(chr($pad), $pad);
return bin2hex(mcrypt_encrypt(MCRYPT_DES, $salt, $key, MCRYPT_MODE_CBC, $salt));
}
Test output:
php > echo get_encrypted_key('Benjamin Franklin');
0b3c6e5df5d747fb3c50de952fece3999768f35b890bc391
php > echo get_encrypted_key('President Franklin D Roosevelt');
c119b50a5a7f8c905a86a43f5694b4d7dd1e8d0577f1ceb32a86fabcea5711e1