Decrypted string is sometimes not same as encrypted source - php

class Auth extends MySQLi {
public function aes_enc($encrypt, $mc_key, $iv) {
$passcrypt = trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), trim($encrypt), MCRYPT_MODE_CBC, $iv));
return $passcrypt;
}
public function aes_dec($decrypt, $mc_key, $iv) {
$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), trim($decrypt), MCRYPT_MODE_CBC, $iv));
return $decrypted;
}
public function salt() {
return str_shuffle('abcdefghijklmnoprsquvzyx0123456789-.,;:_<>');
}
public function iv() {
return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
}
}
And on test.php, following code:
<?
require('Auth.php');
$Auth = new Auth;
$str = "verygudlongpassword";
for ($i = 0; $i < 1000; $i++) {
$salt = sha1($Auth->salt());
$iv = $Auth->iv();
$enc = $Auth->aes_enc($str, $salt, $iv);
$dec = $Auth->aes_dec($enc, $salt, $iv);
if ($str != $dec) {
echo $salt . "<br>\n";
}
}
?>
Sometimes, $dec != $str. Why is this happening? I am not even saving anything into DB atm, so it's not that.
Thanks for help.
i dont really have anything more to say, but site isnt letting me post. (nvm that part)

After reviewing your code and playing with it locally. It would appear that your decryption leaves some whitespace on the decrypted text. I removed the trim() function from all locations except the return value from aes_dec() and the code now encrypts/decrypts your string successfully 1000 times.
So it would seem trimming was the problem and the solution.
class Auth extends MySQLi {
public function aes_enc($encrypt, $mc_key, $iv)
{
$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), $encrypt, MCRYPT_MODE_CBC, $iv);
return $passcrypt;
}
public function aes_dec($decrypt, $mc_key, $iv)
{
$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, substr($mc_key, 0, 32), $decrypt, MCRYPT_MODE_CBC, $iv));
return $decrypted;
}
public function salt()
{
return str_shuffle('abcdefghijklmnoprsquvzyx0123456789-.,;:_<>');
}
public function iv()
{
return mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
}
}
$Auth = new Auth;
$str = "verygudlongpassword";
for ($i = 0; $i < 1000; $i++) {
$salt = sha1($Auth->salt());
$iv = $Auth->iv();
$enc = $Auth->aes_enc($str, $salt, $iv);
$dec = $Auth->aes_dec($enc, $salt, $iv);
if ($str != $dec) {
echo "Decryption failed!<br>\n";
} else {
echo "Decryption success! String: $dec<br>\n";
}
}

Related

php encrypting and decrypting cookies

I have the following class that I am trying to use to encrypt and decrypt my cookies. I need to store user id in cookies for the Keep Me Logged In feature so that the user stays logged in even if he closes the browser and returns later. The following function that I am using is working fine for the encryption. However, it's not working for decryption. I got this class from this question.
$key = 'alabooencryptionkey';
$iv = AES256Encryption::generateIv();
class AES256Encryption {
public const BLOCK_SIZE = 8;
public const IV_LENGTH = 16;
public const CIPHER = 'AES256';
public static function generateIv(bool $allowLessSecure = false): string {
$success = false;
$random = openssl_random_pseudo_bytes(openssl_cipher_iv_length(static::CIPHER));
if(!$success) {
if (function_exists('sodium_randombytes_random16')) {
$random = sodium_randombytes_random16();
}else{
try {
$random = random_bytes(static::IV_LENGTH);
}catch (Exception $e) {
if($allowLessSecure) {
$permitted_chars = implode('',
array_merge(
range('A', 'z'),
range(0, 9),
str_split('~!##$%&*()-=+{};:"<>,.?/\'')
)
);
$random = '';
for($i = 0; $i < static::IV_LENGTH; $i++) {
$random .= $permitted_chars[mt_rand(0, (static::IV_LENGTH) - 1)];
}
}else{
throw new RuntimeException('Unable to generate initialization vector (IV)');
}
}
}
}
return $random;
}
protected static function getPaddedText(string $plainText): string {
$stringLength = strlen($plainText);
if($stringLength % static::BLOCK_SIZE) {
$plainText = str_pad($plainText, $stringLength + static::BLOCK_SIZE - $stringLength % static::BLOCK_SIZE, "\0");
}
return $plainText;
}
public static function encrypt(string $plainText, string $key, string $iv): string {
$plainText = static::getPaddedText($plainText);
return base64_encode(openssl_encrypt($plainText, static::CIPHER, $key, OPENSSL_RAW_DATA, $iv));
}
public static function decrypt(string $encryptedText, string $key, string $iv): string {
return openssl_decrypt(base64_decode($encryptedText), static::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
}
}
I am using it here for encrypting my cookie which works fine.
function setLoginCookieSession($user){
global $key, $iv;
$_SESSION['newchatapp'] = $user;
setcookie("newchatapp", AES256Encryption::encrypt($user, $key, $iv), time()+3600*24*365*10, '/');
}
And here for decrypting which is not working. It returns nothing.
function sessionUser(){
global $key, $iv;
// return (isset($_SESSION['newchatapp']))?$_SESSION['newchatapp']:AES256Encryption::decrypt($_COOKIE['newchatapp'], $key, $iv);
return AES256Encryption::decrypt($_COOKIE['newchatapp'], $key, $iv);
}
Even if I manually input try to decode the encrypted string it still returns nothing.
echo AES256Encryption::decrypt('ianXhsXhh6MWAHliZoshEA%3D%3D', $key, $iv);
This means that the decryption is not working at all. What can I do to make it work?

Why AES Decrypt code doesn't work in php 7.2

I used AES for encrypt the post parameters that send from java to server with volley. so I used below's class in my server for decrypt the post parammeters .
<?php
class MCrypt {
private $hex_iv = '31323334353637383930616263646566'; # converted Java byte code in to HEX and placed it here
private $key = '0FDOUZ.Qz'; #Same as in JAVA
function __construct() {
$this->key = hash('sha256', $this->key, true);
//echo $this->key.'<br/>';
}
function encrypt($str) {
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($str) % $block);
$str .= str_repeat(chr($pad), $pad);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($encrypted);
}
function decrypt($code) {
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));
$str = mdecrypt_generic($td, base64_decode($code));
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $this->strippadding($str);
}
/*
For PKCS7 padding
*/
private function addpadding($string, $blocksize = 16) {
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
private function strippadding($string) {
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if (preg_match("/$slastc{" . $slast . "}/", $string)) {
$string = substr($string, 0, strlen($string) - $slast);
return $string;
} else {
return false;
}
}
function hexToStr($hex)
{
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
}
?>
Also I used below's code in newuser.php file .
<?php
.....
//decrypt
$encryption = new MCrypt();
$phone= $encryption->decrypt($phoneenc);
$password= $encryption->decrypt($passwordenc);
$serialdivice= $encryption->decrypt($serialdiviceenc);
$sequretyQustion= $encryption->decrypt($sequretyQustionenc);
$sequretyAnsewr= $encryption->decrypt($sequretyAnsewrenc);
.... ?>
Before Update php to php7.2 my code worked correctly . But for now It get error for decrypt method when I updated php . so How can i fix it?
I used openssl for both java and php .It's working correctly now.

PHP convert MCRYPT_ENCRYPT to OPENSSL_ENCRYPT (SOAP header)

I need to encrypt some SOAP header fields, and I currently have the following code working in a project with PHP 5.6 version.
function getBaseEncoded($data, $key)
{
$size = $this->pkcs5_pad($data, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB));
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);
$result = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $size, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($result));
}
private function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat (chr($pad), $pad);
}
What happens is that now I have in my hands a similiar project but with PHP 7, and the function MCRYPT is deprecated and I need to switch it to OPENSSL_ENCRYPT.
The code below is my first attempt:
function getBaseEncoded($data, $key)
{
$result = openssl_encrypt($data, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
return trim(base64_encode($result));
}
But I'm now receiving a SOAP error with the message
SoapFault => Could not connect to host
and it got me thinking if the problem is on my new function?
You are missing some initializator vector data.
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$ciphertext = openssl_encrypt(
$data,
'AES-128-ECB',
$key,
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
$iv
);
echo encrypt_openssl($data, $key);
function encrypt_openssl($msg, $key, $iv = null) {
$iv_size = openssl_cipher_iv_length('AES-128-ECB');
if (!$iv) {
$iv = openssl_random_pseudo_bytes($iv_size);
}
$encryptedMessage = openssl_encrypt($msg, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $encryptedMessage);
}

php Encryption not work in 5.6 or later version?

I am using this code to encrypt password but it doesn't work php 5.6 or later versions. Please suggest me new code without changing algo.
please give me new code without changing algorithm.
<?php
class Encryption {
var $skey = "844958uyjd875e89t5f4h6j4h5g"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
?>
Just use password_hash and password_verify. It's the safest way to protect passwords.
For example:
$password_hash = password_hash("yourpassword", PASSWORD_DEFAULT);
if (password_verify('yourpassword', $password_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
http://php.net/manual/en/function.password-hash.php

Looking to convert this JAVA/PHP Encryption code to C#

I work in PHP and looking to convert a piece of code from JAVA/PHP to C# related to encryption , I am novice in C# can anyone help me?
Code is picked from http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php
Also given below - Please help me :
====================================================
/****/
/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;
}
}
Look at MSDN (MicroSoft Developer Network),
at the end of the page there are some examples called RijndaelManaged_Example that show how to encrypt and decypt
http://msdn.microsoft.com/en-us/library/f9df14hc(v=vs.110).aspx

Categories