crypt function PHP showing the salt in plain form - php

I'm using crypt function to create the hash from the string, but when used the salt parameter it's showing the salt parameter in plain form, I know the salt parameter is optional we can exclude that but what is the way to make the salt to not show in the plain form in the hashed string.
Example code
echo crypt('something','$5$rounds=5000$anexamplestring$');
Output for this code is
$5$rounds=5000$anexamplestring$YuRqx9rDLGE1wLc9Bp01/DetFvo6S7Bphn6TgGViCD8
Here the output starting string is same as the crypt function that looks awkward, is there any way around to fix this, or this is the default behavior?

In your case, you can't decrypt it without salt, it will be in the hash.
I do this if you need to encrypt something, then you need openssl and the string can be long, but each time a new one and you can't pick it up without a key.
function get_encrypt($str = false, $key = false)
{
if (!is_string($str)) {
return false;
}
$key = !empty($key) ?: 'b7^FV7867&f)vd6567';
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($str, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
$encrypttext = base64_encode($iv . $hmac . $ciphertext_raw);
return ($encrypttext);
}
function get_decrypt($str = false, $key = false)
{
$key = !empty($key) ?: 'b7^FV7867&f)vd6567';
$c = base64_decode($str);
$ivlen = openssl_cipher_iv_length($cipher = "AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len = 32);
$ciphertext_raw = substr($c, $ivlen + $sha2len);
$decrypttext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
if (hash_equals($hmac, $calcmac)) {
return ($decrypttext);
} else {
return false;
}
}
$str = get_encrypt('something'); // out: ccxCvYCQrsCDC8LA1jrxh3OP38KzLXk5NLxIaSH2W7oDsqUSi3gsmZBq8hnVwuAfCZwt3M1lJhHjFAArHXlrcA==
get_decrypt($str); // out: something

Related

Decrypt encrypted string on a different machine with PHP

I wrote a simple API with PHP that return an encypted string (using openssl_encrypt() function) to the clients/consumers.
When the consumer receives the encrypted string, it can't decrypt it correctly (obviously using the same key) because openssl_decrypt() function return false...
What's wrong?
/* Encryption on server */
$cipher = "aes-128-gcm";
$key = 'my-super-secret-key';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$enc_string = openssl_encrypt($my_string, $cipher, $key, 0, $iv, $tag);
/* Decryption on client */
$cipher = "aes-128-gcm";
$key = 'my-super-secret-key';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$my_string = openssl_decrypt($enc_string, $cipher, $key, 0, $iv, $tag);
$tag = NULL;
$start_string = 'The quick brown fox';
/* Encryption on server */
$cipher = "aes-128-gcm";
$key = 'my-super-secret-key';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$enc_string = openssl_encrypt($start_string, $cipher, $key, 0, $iv, $tag);
echo $enc_string . PHP_EOL;
/* Decryption on client */
$cipher = "aes-128-gcm";
$key = 'my-super-secret-key';
$ivlen = openssl_cipher_iv_length($cipher);
#$iv = openssl_random_pseudo_bytes($ivlen);
$my_string = openssl_decrypt($enc_string, $cipher, $key, 0, $iv, $tag);
echo '>'. $my_string .'<';
OUTPUT
qqajjDNub7pylS68E7QLrHExqA==
>The quick brown fox<
You need a valid $tag and to use the same $iv and $tag when encrypting and decrypting.
So you will need to be able to securely transfer those 2 + the key to the remove machine.

php-encrypt comparing two data

i'm still a newbie and a new coder in encrypting the data in php, i have a data encrypted with iv in the database now the problem is that when the user try to search that data i will compare the data he inputted to the database data in sql kind like of WHERE tbl_column = "user_input". is there any better way to compare two data (plain data check to encrypted data) here is my code.
<?php
$input = 'sample';
$key = "secretkey";
$secretMethod = 'AES-256-CBC';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
echo $database_data = openssl_encrypt('sample', $secretMethod, $key, 0, $iv);
echo $data = $iv.$emessage;
$iv = substr($data, 0, $iv_size);
echo '<br/>Decrypted: '.openssl_decrypt(substr($data, $iv_size), $umethod, $key, 0, $iv);
if($data == $input) {
echo 'equal';
} else {
echo 'not-equal';
}
?>
i am working with this solution for encryption/decryption
1- encryption:
function crypt_val($val){
$token = $val;
$enc_method = 'AES-128-CTR';
$enc_key = openssl_digest(gethostname() . "|" . $key, 'SHA256', true);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($enc_method));
$crypted_token = openssl_encrypt($token, $enc_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
return $crypted_token;
}
2- decryption:
function decrypt_val($val){
$crypted_token = $val;
if(preg_match("/^(.*)::(.*)$/", $crypted_token, $regs)) {
list(, $crypted_token, $enc_iv) = $regs;
$enc_method = 'AES-128-CTR';
$enc_key = openssl_digest(gethostname() . "|" . $key, 'SHA256', true);
$decrypted_token = openssl_decrypt($crypted_token, $enc_method, $enc_key, 0, hex2bin($enc_iv));
return $decrypted_token;
}
}
The first function will crypt an entered string, an the second will decrypt it
Note that $key is your secret key, it will be used for encryption/decryption process

PHP mcrypt and SQL Where for Encrypted Info?

I Have a function where text is encrypted and decrypted. On every refresh the encryption is always different and the decrypted is always the same as the original string. I update to a sql database the encryption. I Can't Use a simple "SELECT * FROM mytable WHERE MyField = 'Myencryption';" because the 'Myencryption' will be different each time. How can I search in SQL an Mycrypt Encryption? Any Suggestions?
My Code is Below: ( I have a PDO SQL Class )
// Encrypt Function
private function encrypt($encrypt, $key){
$encrypt = serialize($encrypt);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
$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;
}
// Decrypt Function
private function 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; }
$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;
} // End Decrypt
$this->db->query("SELECT * FROM `$this->main_db`.`$this->apps_tbl` WHERE `2` = ':db_name'");
$this->db->bind(':db_name', $app_id);
$row = $this->db->single();
SELECT * FROM mytable WHERE 'text' = AES_DECRYPT(MyField, 'Your 256 key');
But if you have many rows in table or weak server, this way may be quite slow.

Simple PHP Encryption / Decryption (Mcrypt, AES)

I'm looking for a simple yet cryptographically strong PHP implementation of AES using Mcrypt.
Hoping to boil it down to a simple pair of functions, $garble = encrypt($key, $payload) and $payload = decrypt($key, $garble).
I'm recently learning about this subject, and am posting this answer as a community wiki to share my knowledge, standing to be corrected.
Mcrypt Documentation
It's my understanding that AES can be achieved using Mcrypt with the following constants as options:
MCRYPT_RIJNDAEL_128 // as cipher
MCRYPT_MODE_CBC // as mode
MCRYPT_MODE_DEV_URANDOM // as random source (for IV)
During encryption, a randomized non-secret initialization vector (IV) should be used to randomize each encryption (so the same encryption never yields the same garble). This IV should be attached to the encryption result in order to be used later, during decryption.
Results should be Base 64 encoded for simple compatibility.
Implementation:
<?php
define('IV_SIZE', mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
function encrypt ($key, $payload) {
$iv = mcrypt_create_iv(IV_SIZE, MCRYPT_DEV_URANDOM);
$crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $payload, MCRYPT_MODE_CBC, $iv);
$combo = $iv . $crypt;
$garble = base64_encode($iv . $crypt);
return $garble;
}
function decrypt ($key, $garble) {
$combo = base64_decode($garble);
$iv = substr($combo, 0, IV_SIZE);
$crypt = substr($combo, IV_SIZE, strlen($combo));
$payload = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypt, MCRYPT_MODE_CBC, $iv);
return $payload;
}
//:::::::::::: TESTING ::::::::::::
$key = "secret-key-is-secret";
$payload = "In 1435 the abbey came into conflict with the townspeople of Bamberg and was plundered.";
// ENCRYPTION
$garble = encrypt($key, $payload);
// DECRYPTION
$end_result = decrypt($key, $garble);
// Outputting Results
echo "Encrypted: ", var_dump($garble), "<br/><br/>";
echo "Decrypted: ", var_dump($end_result);
?>
Output looks like this:
Encrypted: string(152) "4dZcfPgS9DRldq+2pzvi7oAth/baXQOrMmt42la06ZkcmdQATG8mfO+t233MyUXSPYyjnmFMLwwHxpYiDmxvkKvRjLc0qPFfuIG1VrVon5EFxXEFqY6dZnApeE2sRKd2iv8m+DiiiykXBZ+LtRMUCw=="
Decrypted: string(96) "In 1435 the abbey came into conflict with the townspeople of Bamberg and was plundered."
Add function to clean control characters (�).
function clean($string) {
return preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $string);
}
echo "Decrypted: ", clean($end_result);
Sentrapedagang.com
Simple and Usable:
$text= 'Hi, i am sentence';
$secret = 'RaNDoM cHars!##$%%^';
$encrypted = simple_encrypt($text, $secret);
$decrypted = simple_decrypt($encrypted_text, $secret);
codes:
function simple_encrypt($text_to_encrypt, $salt) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, pack('H*', $salt), $text_to_encrypt, MCRYPT_MODE_CBC, $iv = mcrypt_create_iv($iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND))));
}
function simple_decrypt($encrypted, $salt) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack('H*', $salt), base64_decode($encrypted), MCRYPT_MODE_CBC, $iv = mcrypt_create_iv($iv_size=mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND)));
}
Class Mycrypt
Try using this class. Here. All you need to pass is key and string.
class MCrypt
{
const iv = 'fedcba9876543210';
/**
* #param string $str
* #param bool $isBinary whether to encrypt as binary or not. Default is: false
* #return string Encrypted data
*/
public static function encrypt($str, $key="0123456789abcdef", $isBinary = false)
{
$iv = self::iv;
$str = $isBinary ? $str : utf8_decode($str);
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? $encrypted : bin2hex($encrypted);
}
/**
* #param string $code
* #param bool $isBinary whether to decrypt as binary or not. Default is: false
* #return string Decrypted data
*/
public static function decrypt($code, $key="0123456789abcdef", $isBinary = false)
{
$code = $isBinary ? $code : self::hex2bin($code);
$iv = self::iv;
$td = mcrypt_module_open('rijndael-128', ' ', 'cbc', $iv);
mcrypt_generic_init($td, $key, $iv);
$decrypted = mdecrypt_generic($td, $code);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $isBinary ? trim($decrypted) : utf8_encode(trim($decrypted));
}
private static function hex2bin($hexdata)
{
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
How To Use
$var = json_encode(['name'=>['Savatar', 'Flash']]);
$encrypted = MCrypt::encrypt();
$decrypted = MCrypt::decrypt($encrypted);

Encrypting strings in PHP

Currently im using
$key="pass";
$val="secret";
$encp=mcrypt_encrypt(MCRYPT_DES, $key, $val, MCRYPT_MODE_ECB);
But when i call printf($encp)
No value is displayed,im using PHP version 5.2.17
Is there a better way to do it.Please help.
EDIT:
<?PHP
define('SECURE_KEY','Somekey');
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
}
$temp=encrypt("teststring");
printf($temp);
?>
Update (27/09/17):
Since mcrypt_encrypt is DEPRECATED as of PHP 7.1.0. Ive added a simple encrypt/decrypt using openssl.
function encrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// encrypt
$output = openssl_encrypt($string, $method, $key, 0, $iv);
// encode
return base64_encode($output);
}
function decrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// decode
$string = base64_decode($string);
// decrypt
return openssl_decrypt($string, $method, $key, 0, $iv);
}
$str = 'Encrypt this text';
echo "Plain: " .$str. "\n";
// encrypt
$encrypted_str = encrypt($str);
echo "Encrypted: " .$encrypted_str. "\n";
// decrypt
$decrypted_str = decrypt($encrypted_str);
echo "Decrypted: " .$decrypted_str. "\n";
Try these: (PHP < 7.1.0) If your using > PHP 7.1.0 see above.
define('SECURE_KEY','Somekey');//Assigned within a config, pref outside of root dir
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
}
//Simple usage
$encryptedString = encrypt('This String Will Be encrypted');
echo decrypt($encryptedString);
Edited from source - http://php.net/manual/en/function.mcrypt-encrypt.php
Try these PHP functions convert_uuencode and convert_uudecode:
function encrypt_decrypt ($data, $encrypt) {
if ($encrypt == true) {
$output = base64_encode (convert_uuencode ($data));
} else {
$output = convert_uudecode (base64_decode ($data));
}
return $output;
}
$enc_txt = encrypt_decrypt ("PASSWORD TEXT", true);
echo $enc_txt."\n";
// LTQkJTM0VT0vNEQwQDUkNTg1YGBgCmAK
echo encrypt_decrypt ($enc_txt, false);
// PASSWORD TEXT
This is much simpler and does not depend on libraries installed in PHP

Categories