Security of generating keys for AES Encryption - php

I found this following code while researching about AES encryption on the internet. In this code I found that the key and the iv are generated using hash function and uses sha256. I would like to know whether this method is safe for encryption of text using PHP.
The code which I found online is given below,
<?php
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
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;
}
$plain_txt = "This is my plain text";
echo "Plain Text =" .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = " .$encrypted_txt. "\n";
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text =" .$decrypted_txt. "\n";
if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
else echo "FAILED";
echo "\n";
?>

No it is not a secure method to derive an encryption key from a password.
Just using a hash function is not sufficient and just adding a salt does little to improve the security. Instead iterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash. Use a function such as PBKDF2, Rfc2898DeriveBytes, Bcrypt or similar functions. The point is to make the attacker spend a lot of time finding passwords by brute force.
The generally accepted method is PBKDF2 (Password Key Derivation Function 2), sometimes referred to as Rfc2898DeriveBytes in some implementations.
Note: One generally accepted way to handle the IV is to prefix the encrypted message with the IV for use in decryption. The IV does not need to be secret, it does need to be different for each encryption with the same key, this is generally achieved by using a random byte array from a CSPRNG (Cryptographically Secure PseudoRandom Number Generator).

The IV isn't a secret, but should be unique to make two strings encrypted with the same password have different encrypted values. So this is a bad way to generate it. Use http://php.net/manual/kr/function.openssl-random-pseudo-bytes.php or a similar function to generate an unique IV for each time you encrypt some data and store the IV with the data.
#zaph have already commented on the issues with how the key is derived from the password

Related

Using openssl_decrypt() not displaying anything when trying to decrypted an encrypted data

I am trying to decrypt data coming from ionic in PHP but it is not decrypting using openssl_decrypt().
In my ionic app, I was able to encrypt and also test the decryption function which works well. Below are both the encryption and decryption functions:
Encryption
encrypt(key, iv, value){
const encrypted = CryptoJS.AES.encrypt(value, key, { iv: iv });
const encryptedMessage = encrypted.toString();
return encryptedMessage;
}
Decryption
decrypt(value, keys, ivs){
const decryptedMessage = CryptoJS.AES.decrypt(value, keys, { iv: ivs
}).toString(CryptoJS.enc.Utf8);
return decryptedMessage;
}
Encrypted data with key and iv
$iv = "048eb25d7a45ff00";
$key = "feda4f2f67e7aa96";
$encrypted = "U2FsdGVkX1+kBV6Q5BQrjuOdi4WLiu4+QAnDIkzJYv5ATTkiiPVX8VcDUpMqSeIwCfyTNQOosp/9nYDY4Suu4/Lmhh2quKBU7BHGOtKwu9o=";
**To decrypt in PHP**
<?php
// Use openssl_decrypt() function to decrypt the data
$output = openssl_decrypt($encrypted, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
echo $output;
?>
How can I decrypt this?
In the CryptoJS code, the key material is passed as string, which is why it is interpreted as password and a key derivation is applied. The key derivation function used is the OpenSSL proprietary EVP_BytesToKey(). During encryption, CryptoJS.AES.encrypt() does the following:
Generate an 8 bytes salt implicitly.
Derive a 32 bytes key and 16 bytes IV based on the salt and password using EVP_BytesToKey().
Encrypt the plaintext with key and IV, ignoring any explicitly passed IV (here 048eb25d7a45ff00)!
Convert the data to OpenSSL format (by encrypted.toString()): Base64 encoding of the ASCII encoding of Salted__, followed by the 8 bytes salt and the actual ciphertext.
Therefore, decryption must be carried out as follows:
Separate salt and actual ciphertext.
Derive the 32 bytes key and 16 bytes IV from salt and password using EVP_BytesToKey(). Note that the IV 048eb25d7a45ff00 is not needed.
Decrypt the ciphertext with key and IV.
A possible implementation:
// Separate salt and actual ciphertext
$saltCiphertext = base64_decode("U2FsdGVkX1+kBV6Q5BQrjuOdi4WLiu4+QAnDIkzJYv5ATTkiiPVX8VcDUpMqSeIwCfyTNQOosp/9nYDY4Suu4/Lmhh2quKBU7BHGOtKwu9o=");
$salt = substr($saltCiphertext, 8, 8);
$ciphertext = substr($saltCiphertext, 16);
// Separate key and IV
$keyIv = EVP_BytesToKey($salt, "feda4f2f67e7aa96");
$key = substr($keyIv, 0, 32);
$iv = substr($keyIv, 32, 16);
// Decrypt using key and IV
$decrypted = openssl_decrypt($ciphertext, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
print($decrypted . PHP_EOL); // {"username":"07069605705","password":"father2242"}
// KDF EVP_BytesToKey()
function EVP_BytesToKey($salt, $password) {
$bytes = ''; $last = '';
while(strlen($bytes) < 48) {
$last = hash('md5', $last . $password . $salt, true);
$bytes.= $last;
}
return $bytes;
}
Note: EVP_BytesToKey() is deemed insecure nowadays and should not be used. A more secure alternative is PBKDF2 which is supported by both CryptoJS and PHP.

How to encrypt with openssl_encrypt using AES and salt in place of Base64

Currently I am using openssl_encrypt to encrypt the data and it return base64 value. I have to use AES encryption with salt.
Can any one tell how to implement AES encryption with salt?
Here is the code I use:
function encrypt_decrypt($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret_iv), 0, 16);
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;
}
Always use tested libraries for such purposes. Your encryption is vulnerable and completely insecure because you're not using IV correctly.
Consider using defuse/php-encryption library and get rid of what you've done.
Why is what you've done wrong:
The same IV (initialization vector) is used.
There is no salt in encryption, it's called Initialization Vector and it must be different every time you encrypt - your IV is always the same
When encryption is done, you must deliver the encrypted data and IV - you are not returning IV with encryption result, only the result.
Currently, you are not doing what I outlined and that's why you should invest your time into using a library that takes care of encryption so you don't roll out your own, insecure implementation. I'm deliberately not posting the code required for this encryption to work from fear that someone will use it, instead of library that I linked. Always use libraries made by other people if you have no idea what you're doing.
In case someone needs it, and yes you can add salt using openssl_pbkdf2
$ciphertext_b64 = "";
$plaintext = "hello alice";
$password = "XhcwO1NNI1Xi43EVAtVPS1vknOGgsgIu16OmUAtzlGoHtaPYWwLqxxAEHcBbocWiaYYtBSlgvkn5rVBu";
$salt = "CK4OGOAtec0zgbNoCK4OGOAtec0zgbNoCK4OGOAtec0zgbNoCK4OGOAtec0zgbNo";
$iv = "LQjFLCU3sAVplBC3";
$iterations = 1000;
$keyLength = 32;
$prepared_key = openssl_pbkdf2($password, $salt, $keyLength, $iterations, "sha256");
$ciphertext_b64 = base64_encode(openssl_encrypt($plaintext,"AES-256-CBC", $prepared_key,OPENSSL_RAW_DATA, $iv));
echo $ciphertext_b64 . "<br/>";
$plaintext = openssl_decrypt(base64_decode($ciphertext_b64),"AES-256-CBC", $prepared_key,OPENSSL_RAW_DATA, $iv);
echo $plaintext . "<br/>";

How to stretch user password for encryption in PHP?

I thought I understood this, but my program won't decrypt and says the key is wrong, so I realize I need help. I thought the algorithm went:
Encryption:
Get user password P
Call hash_pbkdf2 to stretch P into a key K_pass_1
Call another key-stretching algorithm (I don't know which, haven't done this yet) to turn K_pass_1 into K_auth_1
Encrypt data with K_auth_1 K_pass_1
Decryption:
Get user password P
Call hash_pbkdf2 to stretch P into a key K_pass_2
as above
Decrypt data with K_auth_2 K_pass_2
Is that not correct? (Edit: It turns out it is, but that was too high level - my problem was more specific.)
Edit: Here is my code:
<?php
$GLOBALS['key_size'] = 32; // 256 bits
class WeakCryptographyException extends Exception {
public function errorMessage() {
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b>There was a problem creating strong pseudo-random bytes: system may be broken or old.';
return $errorMsg;
}
}
class FailedCryptographyException extends Exception {
public function errorMessage() {
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b>There was a problem with encryption/decryption.';
return $errorMsg;
}
}
class InvalidHashException extends Exception {
public function errorMessage() {
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b>Password verification failed.';
return $errorMsg;
}
}
function generate_key_from_password($password) {
$iterations = 100000;
$salt = openssl_random_pseudo_bytes($GLOBALS['key_size'], $strong);
$output = hash_pbkdf2("sha256", $password, $salt, $iterations, $GLOBALS['key_size'], true);
if ($strong) {
return $output;
} else {
// system did not use a cryptographically strong algorithm to produce the pseudo-random bytes
throw new WeakCryptographyException();
}
}
/** Encrypts the input data with Authenticated Encryption. We specifically use
* openssl_encrypt($data, 'AES-256-CBC', $encryption_key, OPENSSL_RAW_DATA, $iv), where $iv is a 256-bit nonce
* generated with openssl_random_pseudo_bytes. Then we hash the output with bcrypt and prepend the hash and iv to
* the ciphertext to create an 'authenticated ciphertext' that can be fed directly into the my_decrypt method.
*
* #param $data string; The data to be encrypted
* #param $encryption_key string; A 256-bit key (which PHP reads as a string of characters)
* #return string The authenticated ciphertext, with the format: $hash . $iv . $ciphertext
* #throws FailedCryptographyException If there are errors during encryption
* #throws WeakCryptographyException If the openssl_random_pseudo_bytes method fails to use a cryptographically strong
* algorithm to produce pseudo-random bytes.
*
* Note that in creating a hash for the ciphertext, we use bcrypt instead of sha2. In particular, the difference in lines is:
* bcrypt: password_hash($ciphertext, PASSWORD_DEFAULT);
* sha2: hash_hmac('sha256', $ciphertext, $auth_key, true);
*
* And we chose this despite the fact that sha2 is the only acceptable hashing algorithm for NIST, because:
* 1. bcrypt is also widely considered a cryptographically secure hashing algorithm.
* 2. sha2 is not supported by PHP 5's password_hash method and bcrypt is.
* 3. PHP's password_verify method uses a hash created by the password_hash method and compares hashes in a way that is
* safe against timing attacks. There is no known way to make this comparison for other hashes in PHP.
*/
function my_openssl_encrypt($data, $encryption_key) {
$iv_size = 16; // 128 bits to match the block size for AES
$iv = openssl_random_pseudo_bytes($iv_size, $strong);
if (!$strong) {
// system did not use a cryptographically strong algorithm to produce the bytes, don't consider them pseudo-random
throw new WeakCryptographyException();
}
$ciphertext = openssl_encrypt(
$data, // data
'AES-256-CBC', // cipher and mode
$encryption_key, // secret key
OPENSSL_RAW_DATA, // options: we use openssl padding
$iv // initialisation vector
);
if (!$ciphertext) {
$errormes = "";
while ($msg = openssl_error_string())
$errormes .= $msg . "<br />";
throw new FailedCryptographyException($errormes);
}
$auth = password_hash($ciphertext, PASSWORD_DEFAULT);
$auth_enc_name = $auth . $iv . $ciphertext;
return $auth_enc_name;
}
/** Decrypts a ciphertext encrypted with the method my_openssl_encrypt. First checks if the hash of the ciphertext
* matches the hash supplied in the input ciphertext, then decrypts the message if so. We specifically use
* openssl_decrypt($enc_name, 'AES-256-CBC', $encryption_key, OPENSSL_RAW_DATA, $iv), where $iv is a 256-bit nonce
* stored with the ciphertext.
*
* #param $ciphertext string; An authenticated ciphertext produced by my_openssl_encrypt
* #param $encryption_key string; A 256-bit key (which PHP reads as a string of characters)
* #return string The decrypted plaintext
* #throws FailedCryptographyException If there are errors during decryption
* #throws InvalidHashException If the password hash doesn't match the stored hash (this will almost always happen when
* any bits in the ciphertext are changed)
*/
function my_openssl_decrypt($ciphertext, $encryption_key) {
// verification
$auth = substr($ciphertext, 0, 60);
$iv = substr($ciphertext, 60, 16);
$enc_name = substr($ciphertext, 76);
if (password_verify($enc_name, $auth)) {
// perform decryption
$output = openssl_decrypt(
$enc_name,
'AES-256-CBC',
$encryption_key,
OPENSSL_RAW_DATA,
$iv
);
if (!$output) {
$errormes = "";
while ($msg = openssl_error_string())
$errormes .= $msg . "<br />";
throw new FailedCryptographyException($errormes);
}
return $output;
} else {
throw new InvalidHashException();
}
}
// Testing
function testEnc($message)
{
$encryption_key = generate_key_from_password("123456");
$auth_ciphertext = my_openssl_encrypt($message, $encryption_key);
$encryption_key = generate_key_from_password("123456");
$plaintext = my_openssl_decrypt($auth_ciphertext, $encryption_key);
echo "<p>Original message: " . $message .
"</p><p>Encryption (hex): " . bin2hex($auth_ciphertext) .
"</p><p>Plaintext: " . $plaintext . "</p>";
echo "<p>Bytes of input: " . (strlen($message) * 2) .
"<br />Bytes of ciphertext: " . (strlen($auth_ciphertext) * 2) . "</p>";
}
echo '<p>Test 1: ';
testEnc('Hello World');
echo '</p>';
The problem is in the function:
function generate_key_from_password($password)
the line:
$salt = openssl_random_pseudo_bytes($GLOBALS['key_size'], $strong);
The same salt needs to be used in order to derive the same key.
A salt needs to be created outside of the generate_key_from_password function and passed in and it needs to be the same salt for encryption and decryption. This is usually done by creating a salt in the encryption function, passing it into the PBKDF2 function and prepending the salt to the encrypted output in the same manner as the iv. Then the same salt is available to the decryption function.
It is little things like this that make using encryption securely difficult. See RNCryptor-php and RNCryptor-Spec for an example that also includes authentication, the iteration count and a version.
Skip step 3, it is not necessary.
Make sure the key and iv are exactly the correct length. Insure you are using CBC mode and PKCS#7 (or PKCS#5).
Use the optional 5th parameter $length for hash_pbkdf2():
var_dump(hash_pbkdf2("sha256", "foobar", "salty", 100));
// string(64) "5d808ee6539c7d0437e857a586c844900bf0969d1af70aea4c3848550d9038ab"
var_dump(hash_pbkdf2("sha256", "foobar", "salty", 100, 32));
// string(32) "5d808ee6539c7d0437e857a586c84490"
var_dump(hash_pbkdf2("sha256", "foobar", "salty", 100, 128));
// string(128) "5d808ee6539c7d0437e857a586c844900bf0969d1af70aea4c3848550d9038abb2853bf0cf24c9d010555394f958fa647a04b232f993c35916977b4ef5a57dcc"
You probably also want raw output, so read the above-linked doc page for the method and caveats to that.

Function encryption AES-256-CBC, search mysql

I work with PHP and MySQL, and enter data in encrypted form using this function in PHP:
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
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;
}
And I ended up running into a huge problem.
I need to search the table, and need to use the MySQL LIKE function.
How can I do this?
I looked for documentation and found that MySQL has the AES encryption, but I'm completely lost.
This function written in PHP MySQL exists, or is to make it work?
When you enter ciphertext into MySQL, that
has been encrypted outside of MySQL
does not preserve likeness (as most encryptions don't)
you can't perform a LIKE search on it.
If you move encryption into the database, you can perform LIKE searches, but be prepared to take a heavy computational performance hit: Basically MySQL has to decrypt the complete column in addition to the cost involved with the LIKE itself.
The best option is to search for some redesign options, that allow you to simply not do that.

openssl_decrypt () function not working, returning null

i used openssl_encrypt and openssl_decrypt function but the decrypt part is not returning any value, whereas using the same key Encrypt is working fine.
here is the function which i used. the variable $decrypted always return a null .
every small help will be appreciated
function deCryption($value)
{
$methods = openssl_get_cipher_methods();
$clefSecrete = "flight";
echo '<pre>';
foreach ($methods as $method) {
//$encrypted = openssl_encrypt($texteACrypter, $method, $clefSecrete); ----this was used for encryption
$decrypted = openssl_decrypt($value, $method, $clefSecrete);
echo "value=".$decrypted;
echo $method . ' : '. $decrypted . "\n";
break;
}
echo '</pre>';
return $decrypted;
}
I had exactly the same problem, I then googled my question and ended up here, on the same question that I had asked. So I had to search elsewhere.
I found this article useful in explaining the shortcoming of the official php documentation. Another article with similar content is here.
In the end it boils down to the key/password. What the openssl_encrypt library expects is a key NOT A PASSWORD. And the size of key must be the size of cipher’s intrinsic key size. The first article says if you provide a longer key, the excess is discarded and a key shorter than expected is padded with zero, i.e. \x00 bytes. I have not tested this fact.
I have edited your code to read as below.
The idea I have used is that the size of the initial vector that a cipher expects is also the size of the key it expects. So here, I am passing a key not a password as you were doing. Simply find a way turning your password into a key.
In your code, you did not pass options and the iv (initialization vector).
The iv is a string the cipher 'mixes' with the plaintext before encryption. So what the cipher encrypts is this 'mixture'. Is this important? Yes! Without this 'mixing', a pair of identical plaintexts would result into a pair of identical ciphertexts, which can lead to an attack; if two identical plaintext-ciphertext pairs are not from the same user, these two users are using the same key! A unique iv for each plaintext therefore ensures that no two plaintexts result into identical ciphertexts. In other words, the iv is a salt.
$plaintext = 'Testing OpenSSL Functions';
$methods = openssl_get_cipher_methods();
//$clefSecrete = 'flight';
echo '<pre>';
foreach ($methods as $method) {
$ivlen = openssl_cipher_iv_length($method);
$clefSecrete = openssl_random_pseudo_bytes($ivlen);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = openssl_encrypt($plaintext, $method, $clefSecrete, OPENSSL_RAW_DATA, $iv);
$decrypted = openssl_decrypt($encrypted, $method, $clefSecrete, OPENSSL_RAW_DATA, $iv);
echo 'plaintext='.$plaintext. "\n";
echo 'cipher='.$method. "\n";
echo 'encrypted to: '.$encrypted. "\n";
echo 'decrypted to: '.$decrypted. "\n\n";
}
echo '</pre>';

Categories