The command "openssl passwd -1" uses MD5 based BSD password algorithm 1 to compute a string hash.
Example:
openssl passwd -1
$1$./j/us.N$P2tq6IkO0Zu2d3uqkEHpv.
How do I implement exactly the same functionality in PHP? I'd like it to be a native PHP function, rather than something return by exec/shell_exec.
Example code
<?php
define('KEY', 'scret key');
function encrypt($value)
{
$iv = openssl_random_pseudo_bytes(16);
$encrypt = openssl_encrypt($value, 'AES-128-CBC', KEY, 0, $iv);
return base64_encode($encrypt . ':::' . $iv);
}
function decrypt($data)
{
$data = base64_decode($data);
list($data, $iv) = explode(':::', $data);
return openssl_decrypt($data, 'AES-128-CBC', KEY, 0, $iv);
}
$enc = encrypt('password');
echo decrypt($enc);
Related
I want to encrypt data in livecode using mergAESEncryptWithKey pData,pKey,pIV,[pMode],[pKeySize],[pPadding]. The encrypted data is then posted to php. PhP decrypts the data using the same function, does something with the data and then encrypts the results and posts them to livecode. Livecode then decrypts the data from php
My PHP Code looks like this (This works perfect)
function encrypt($plaintext, $salt) {
$method = "AES-256-CBC";
$key = hash('sha256', $salt, true);
$iv = openssl_random_pseudo_bytes(32);
$ciphertext = openssl_encrypt($plaintext, $method, $key, $iv);
$hash = hash_hmac('sha256', $ciphertext . $iv, $key, true);
return $iv . $hash . $ciphertext;
}
function decrypt($ivHashCiphertext, $salt) {
$method = "AES-256-CBC";
$iv = substr($ivHashCiphertext, 0, 32);
$hash = substr($ivHashCiphertext, 32, 48);
$ciphertext = substr($ivHashCiphertext, 64);
$key = hash('sha256', $salt, true);
//if (!hash_equals(hash_hmac('sha256', $ciphertext . $iv, $key, true), $hash)) return null;
return openssl_decrypt($ciphertext, $method, $key, $iv);
}
echo $encrypted."</br>";
echo "----------------------------The message is:<br/>";
echo decrypt($encrypted, 'hashsalt');
For most of you who just don't know but still want to post good for nothing comments, I figured it out. #Sammitch and #Mark asking a question don't mean someone is stupid.
/*
* Encrypt or decrypt data using
* AES-256-CBC
*/
function encrypt_decrypt($mode,$data,$key,$salt){
//define the cipher method
$ciphering = "AES-256-CBC";
// Use OpenSSl Encryption method. This works on PHP 7.2 and above
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
if($mode=="encrypt"){
// Use openssl_encrypt() function to encrypt the data
$Data = openssl_encrypt($data, $ciphering, $key, $options, $salt);
}else{
// Use openssl_decrypt() function to decrypt the data
$Data = openssl_decrypt($data, $ciphering, $key,$options, $salt);
}
return $Data;
}
Oooh and this is for livecode
//encrypt
encrypt tString using "aes-256-cbc" with key theKey and IV saltHash at 256 bit
//decrypt
decrypt base64Decode(varEnc) using "aes-256-cbc" with key theKey and IV saltHash at 256 bit
m using
public function encrypt($plain_str,$key)
{
$str= mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plain_str, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND));
$str = urlencode(base64_encode($str));
return $str ;
}
public function decrypt($cipher_str,$key)
{
$str = urldecode(base64_decode($cipher_str));
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND));
}
on crypting :201433~58~g#fds.com~20140820142427
i get : %2BAihYMLwpwrsmL4lSGGzwFTfonvdCyOb%2BCGEUJ%2F%2BE%2F7ZnvgwFRYFtlazQeSrVjUjyaaGZADK8%2BZyynIGxyt4VQ%3D%3D
on decrypting : %2BAihYMLwpwrsmL4lSGGzwFTfonvdCyOb%2BCGEUJ%2F%2BE%2F7ZnvgwFRYFtlazQeSrVjUjyaaGZADK8%2BZyynIGxyt4VQ%3D%3D
i get :201433~58~g#fds.com~20140820142427 back but
when string is malformed like some character removed
like this : %2BAihYMLwpwrsmL4lSGGzwFTfonvdCyOb%2BCGEUJ%2F%2BE%2F7Z
on decrypting i get : 201433~58~g#fds.com~201408201424O#¿W«Gݽˋ¯ È#'oP´ŸØw\Â⦑
How can i detect this anomoly ?
First of all, I'd like to list some flaws in your code:
Don't use ECB mode.
You are encrypting using MCRYPT_RIJNDAEL_128, but you're getting the IV size for MCRYPT_RIJNDAEL_256. (btw, IV is ignored in ECB mode, which is one of the reasons why not to use it)
You are also using MCRYPT_RAND as your randomness source, which is not secure. You should use MCRYPT_DEV_URANDOM (that is also the new default in PHP 5.6).
You don't have to urlencode() the resulting ciphertext, Base64 encoding is URL-safe.
Now, to answer your question ... this is done via a HMAC. The easiest way to use a HMAC is to prepend the cipher-text with it (which you should do with the IV as well; don't worry, it's not a secret):
public function encrypt($plainText, $encKey, $hmacKey)
{
$ivSize = mcrypt_get_iv_size('rijndael-128', 'ctr');
$iv = mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
$cipherText = mcrypt_encrypt('rijndael-128', $encKey, $plainText, 'ctr', $iv);
$cipherText = $iv.$cipherText;
$hmac = hash_hmac('sha256', $cipherText, $hmacKey, true);
return base64_encode($hmac.$cipherText);
}
public function decrypt($cipherText, $encKey, $hmacKey)
{
$cipherText = base64_decode($cipherText);
if (strlen($cipherText) <= 32)
{
throw new Exception('Authentication failed!');
}
$recvHmac = substr($cipherText, 0, 32);
$cipherText = substr($cipherText, 32);
$calcHmac = hash_hmac('sha256', $cipherText, $hmacKey, true);
if ( ! hash_equals($recvHmac, $calcHmac))
{
throw new Exception('Authentication failed!');
}
$ivSize = mcrypt_get_iv_size('rijndael-128', 'ctr');
$iv = substr($cipherText, $ivSize);
$cipherText = substr($cipherText, $ivSize);
return mcrypt_decrypt('rijndael-128', $encKey, $cipherText, 'ctr', $iv);
}
Please note that the encryption key and HMAC key are different - they most NOT be the same key. Also, for Rijndael-128, you should create a 128-bit (or 16-byte) random key, it is not something that you can just type in with your keyboard. Here's how to generate one:
$encKey = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
I want to know that can I use this encrypt-decrypt script for password encryption and put it into database?
And what will be the sql table password column structure(currently it is password varchar(32) NOT NULL).
Please note that this script is using a 32-byte hexadecimal key as encryption key.
<?php
define('ENCRYPTION_KEY', '32-byte hexadecimal encryption key');
function mc_encrypt($encrypt, $key)
{
$encrypt = serialize($encrypt);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
$key = pack('H*', $key);
$mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));
$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);
$encoded = base64_encode($passcrypt).'|'.base64_encode($iv);
return $encoded;
}
function mc_decrypt($decrypt, $key)
{
$decrypt = explode('|', $decrypt);
$decoded = base64_decode($decrypt[0]);
$iv = base64_decode($decrypt[1]);
if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }
$key = pack('H*', $key);
$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));
$mac = substr($decrypted, -64);
$decrypted = substr($decrypted, 0, -64);
$calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));
if($calcmac!==$mac){ return false; }
$decrypted = unserialize($decrypted);
return $decrypted;
}
?>
You should not store passwords - with or without encryption - unless strictly required (i.e. dealing with older protocols). Instead use a password hash function based on a PBKDF such as PBKDF2, bcrypt or scrypt.
Note that the encryption does not use AES but Rijndael with a block size of 256 bits. Also note that the key handling is suboptimal, it's easy to make mistakes with regards to the key parameter. Otherwise the code looks OK at first glance.
i am try to encrypt following data using the 3des(CBC) using a secretkey and IV spec key in php but i am not getting the same output which i get on this online tool (http://symmetric-ciphers.online-domain-tools.com/)
//input
$data = "Id=120278;timestamp=2009-02-05 08:28:39.195";
$key = "80127ECD5E40BB25DB14354A3795880DF2B459BB08E1EE6D";
$iv = "331BA9C5A7446C98";
//output from online tool. I should get the same result in my php code
$result = "1C80CBCE1713128176499C7A3DFB8779156B31B8DEF2F667A7100F1C3AEFABACB24283CFDF 5D312D A0074897138684BC";
following the PHP code i tried
$string = "Id=120278;timestamp=2009-02-05 08:28:39.195";
$iv = "331BA9C5A7446C98";
$passphrase = "80127ECD5E40BB25DB14354A3795880DF2B459BB08E1EE6D";
$encryptedString = encryptString($string, $passphrase, $iv);
function encryptString($unencryptedText, $passphrase, $iv) {
$enc = mcrypt_encrypt(MCRYPT_3DES, $passphrase, $unencryptedText, MCRYPT_MODE_CBC, $iv);
return base64_encode($enc);
}
Try this:
function encrypt3DES($key,$iv,$text_enc){
$block = mcrypt_get_block_size('tripledes', 'cbc');
$pad = $block - (strlen($text_enc) % $block);
$text_enc .= str_repeat(chr($pad), $pad);
$text_enc = mcrypt_encrypt(MCRYPT_3DES, $key, $text_enc, MCRYPT_MODE_CBC, $iv);
$text_enc = base64_encode ($text_enc);
return $text_enc;
}
I am trying to come up with a way to have PHP encrypt a file. I used to just use a PHP system call to run a script that encoded the file:
#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -salt -k $1 -in $2
Argument 1 was the password to use and argument 2 is the data. I then use a second script on a computer to de-crypt the file.
#!/bin/sh
/usr/bin/openssl aes-256-cbc -a -d -salt -k $1 -in $2
This method of encrypting will not work on a production host as the PHP system call is disabled. I also would prefer not the change the decode function if at all possible.
Is there a way to replicate the above encrypt function using only PHP?
Take a look at mcyrpt_encrypt():
string mcrypt_encrypt ( string $cipher , string $key , string $data ,
string $mode [, string $iv ] )
Set $cipher to MCRYPT_RIJNDAEL_128 (AES-128), and $mode to MCRYPT_MODE_CBC.
Then use base64_encode() to generate a base-64 encoded output (ie: what the -a option
does).
openssl derives the key and IV as follows:
Key = MD5(Password + Salt)
IV = MD5(Key + Password + Salt)
Where Salt is a 8 byte salt. With this in mind, I created simple encrypt() and decrypt() routines:
function ssl_encrypt($pass, $data) {
$salt = substr(md5(mt_rand(), true), 8);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$ct = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $key, $data,
MCRYPT_MODE_CBC, $iv);
return base64_encode('Salted__' . $salt . $ct);
}
function ssl_decrypt($pass, $data) {
$data = base64_decode($data);
$salt = substr($data, 8, 8);
$ct = substr($data, 16);
$key = md5($pass . $salt, true);
$iv = md5($key . $pass . $salt, true);
$pt = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $ct,
MCRYPT_MODE_CBC, $iv);
return $pt;
}
The parameter $data takes the string to be encrypted. If you want to encrypt a file, you'll have to get it via file_get_contents() or similar and then give that to the function.
Usage:
echo ssl_encrypt('super secret key', 'Hello World');
Generates something like (will change every time because of the random salt):
U2FsdGVkX18uygnq8bZYi6f62FzaeAnyB90U6v+Pyrk=
As stated above in the comments padding is necessary to make this work. The function below will make a file that can be decrypted on the command line like this:
openssl enc -d -aes-256-cbc -a -salt -in test.txt
The test.txt file is created from the output of the ssl_encrypt function below.
function ssl_encrypt($pass, $data)
{
// Set a random salt
$salt = substr(md5(mt_rand(), true), 8);
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($data) % $block);
$data = $data . str_repeat(chr($pad), $pad);
// Setup encryption parameters
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, "", MCRYPT_MODE_CBC, "");
$key_len = mcrypt_enc_get_key_size($td);
$iv_len = mcrypt_enc_get_iv_size($td);
$total_len = $key_len + $iv_len;
$salted = '';
$dx = '';
// Salt the key and iv
while (strlen($salted) < $total_len)
{
$dx = md5($dx.$pass.$salt, true);
$salted .= $dx;
}
$key = substr($salted,0,$key_len);
$iv = substr($salted,$key_len,$iv_len);
mcrypt_generic_init($td, $key, $iv);
$encrypted_data = mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return chunk_split(base64_encode('Salted__' . $salt . $encrypted_data),32,"\r\n");
}
Example Usage:
$plainText = "Secret Message";
$password = "SecretPassword";
$test = ssl_encrypt($password, $plainText);
$file = fopen('test.txt', 'wb');
// Write the Base64 encrypted output to a file.
fwrite($file, $test);
fclose($file);
// Show the output on the screen
echo $test;
References: http://juan.boxfi.com/2010/03/16/write-openssl-files-in-php/
Perhaps PHP's OpenSSL library?