Error when decrypting data sent from android in php using jsonparser - php

I'm trying to decrypt data received from Android using HTTP request (Jsonparser) in my server, lines that decrypt the data are commented below in the code. The error appears in android : Error parsing data org.json.JSONException and data is not passed to the server. And when I comment the lines the data arrives at the server normally. How can I decrypt the data before inserting them into the database?
<?php
include("dbConnect.php");
$ID =$_POST["id"];
$Tencrypted =$_POST["temp"];
$Pencrypted =$_POST["pulse"];
$Mencrypted =$_POST["motion"];
//$mcrypt = new MCrypt();
//$Tdecrypted = $mcrypt->decrypt($Tencrypted);
//$Pdecrypted = $mcrypt->decrypt($Pencrypted);
//$Mdecrypted = $mcrypt->decrypt($Mencrypted);
if($ID=="1")
$query = "INSERT INTO William(Temperature,Pulse,Motion) VALUES('$Tencrypted','$Pencrypted','$Mencrypted')";
else if($ID=="2")
$query = "INSERT INTO Jack(Temperature,Pulse,Motion) VALUES('$Tencrypted','$Pencrypted','$Mdecrypted')";
else if($ID=="3")
$query = "INSERT INTO Sam(Temperature,Pulse,Motion) VALUES('$Tencrypted','$Pencrypted','$Mencrypted')";
$result = mysql_query($query) or die(mysql_error());
$arr=array('success'=>$result);
echo json_encode($arr);
/*class MCrypt
{
private $iv = 'fedcba9876543210'; #Same as in JAVA
private $key = '0123456789abcdef'; #Same as in JAVA
function __construct()
{
}
* #param string $str
* #param bool $isBinary whether to encrypt as binary or not. Default is: false
* #return string Encrypted data
function encrypt($str, $isBinary = false)
{
$iv = $this->iv;
$str = $isBinary ? $str : utf8_decode($str);
$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 $isBinary ? $encrypted : bin2hex($encrypted);
}
* #param string $code
* #param bool $isBinary whether to decrypt as binary or not. Default is: false
* #return string Decrypted data
function decrypt($code, $isBinary = false)
{
$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;
}
}
*/
?>
Thanks for your patience and time in reading the code. Please help me.

Related

Converting MCRYPT to OPENSSL [duplicate]

This question already has an answer here:
Upgrading my encryption library from Mcrypt to OpenSSL
(1 answer)
Closed 3 years ago.
I inherited a project that was coded back in the PHP 5.X days. The site is running on PHP 7.1 right now and using the MCRYPT library for it's encryption and decryption functions.
I need to upgrade to PHP 7.2, which means bye bye MCRYPT!
Not being familiar with encryption is causing issues with trying to convert to OPENSSL
Below is the code that is currently in place.
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$enc = base64_decode($encryptedText);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $enc, MCRYPT_MODE_ECB, $key), "\x80");
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $paddedPlainText, MCRYPT_MODE_ECB, $key);
return base64_encode($enc);
}
I have looked over several other StackOverflow posts that go over this exact topic of converting from MCRYPT to OPENSSL, and based on everything I have read, I came up with the following code, which doesn't work.
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = base64_decode($encryptedText);
return trim(openssl_decrypt($enc, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = openssl_encrypt($plaintext, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
return base64_encode($enc);
}
I am not sure, but I have a feeling the issue has to do with the padding of the text in the old encryption function this is causing the new code not to work. I don't know how to integrate that into the OPENSSL functions, if that is indeed the problem.
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
Again, not being familiar with encryption, any/all help is appreciated so I can figure out and understand what I am doing wrong.
I've dealt with this when upgrading my user password encryption. In pseudologic, you just need something like this:
<?php
if ($whatever === $this->decryptNew($var)) {
// business as usual
} elseif ($whatever === $this->decryptOldWay($var)) {
// encrypt as the new way!
$encrypted = $this->encryptNew($whatever);
// save!
// Back to business as usual!
}
Here's my SSl class. Give it a try:
class Ssl
{
private $cipher = "aes-128-gcm";
private $options = 0;
/**
* #param string $plaintext
* #return array
*/
public function encrypt($plaintext)
{
$key = \openssl_random_pseudo_bytes(16);
$ivlen = \openssl_cipher_iv_length($this->cipher);
$iv = \openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $this->cipher, $key, $this->options, $iv,$tag);
return array(
'key' => \bin2hex($key),
'iv' => \bin2hex($iv),
'tag' => \bin2hex($tag),
'ciphertext' => $ciphertext,
);
}
/**
* #param string $json
* #return false|string
*/
public function decrypt($json, $key)
{
$data = \json_decode($json);
$result = \openssl_decrypt($data->ciphertext, $this->cipher, \hex2bin($key), $this->options, \hex2bin($data->iv), \hex2bin($data->tag));
return \json_decode($result, true);
}
}

Decryption data using php rijndael-128 decryption

I'm trying to decrypt data in PHP, I tried this code, but it doesn't print "almost" nor the decrypted data nor "finish". It only prints this line "4b3b798e708d81a939ca084d387136145".
Here is my code :
<?php
class MCrypt
{
private $iv = 'fedcba9876543210'; #Same as in JAVA
private $key = '0123456789abcdef'; #Same as in JAVA
function __construct()
{
}
/**
* #param string $str
* #param bool $isBinary whether to encrypt as binary or not. Default is: false
* #return string Encrypted data
*/
function encrypt($str, $isBinary = false)
{
echo "3";
$iv = $this->iv;
$str = $isBinary ? $str : utf8_decode($str);
$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 $isBinary ? $encrypted : bin2hex($encrypted);
}
/**
* #param string $code
* #param bool $isBinary whether to decrypt as binary or not. Default is: false
* #return string Decrypted data
*/
function decrypt($code, $isBinary = false)
{
echo "4";
$code = $isBinary ? $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 $isBinary ? trim($decrypted) : utf8_encode(trim($decrypted));
}
protected function hex2bin($hexdata)
{
echo "5";
$bindata = '';
for ($i = 0; $i < strlen($hexdata); $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
}
$encrypted="4b3b798e708d81a939ca084d387136";
echo $encrypted;
$mcrypt = new MCrypt();
echo "1";
$decrypted = $mcrypt->decrypt($encrypted);
echo "almost";
echo $decrypted;
echo "finish";
?>

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);

3DES PHP Encryption Not Decrypting Properly

I'm using the following code to encrypt information that will be passed to an external site on the end of the link URL. Right now it's able to do the encrypting and decrypting itself, but when I go to online Decryptors (online-domain-tools.com, tools4noobs.com) I'm seeing extra symbols added or it's not showing the right content whatsoever. Of course I'm new to this. What I have, I have pieced together from other questions (php-equivalent-for-java-triple-des-encryption-decryption, php-equivalent-encryption-decryption-tripledes, php-encrypt-decrypt-with-tripledes-pkcs7-and-ecb). Thanks for any help or direction!
I can only use 3DES with CBC.
PHP Code:
$key = "12AB12AB12AB12AB12AB12AB";
$iv = "12AB12AB";
$cipher = mcrypt_module_open(MCRYPT_3DES, '', 'cbc', '');
// MESSAGE
$message = "email=billysmith#afakeemail.com&account=987654321&role=2";
echo 'Message::: ' .$message .'<br />';
// ENCRYPTED
$encrypted = Encryptor($message);
echo 'Encrypted::: ' .$encrypted .'<br />';
// DECRYPTED
$decrypted = Decryptor($encrypted);
echo 'Decrypted::: ' .$decrypted .'<br />';
function Encryptor($buffer) {
global $key, $iv, $cipher;
// get the amount of bytes to pad
$extra = 8 - (strlen($buffer) % 8);
// add the zero padding
if($extra > 0) {
for($i = 0; $i < $extra; $i++) {
$buffer .= "\0";
}
}
mcrypt_generic_init($cipher, $key, $iv);
$result = bin2hex(mcrypt_generic($cipher, $buffer));
mcrypt_generic_deinit($cipher);
return $result;
}
function Decryptor($buffer) {
global $key, $iv, $cipher;
mcrypt_generic_init($cipher, $key, $iv);
$result = rtrim(mdecrypt_generic($cipher, hex2bin($buffer)), "\0");
mcrypt_generic_deinit($cipher);
return $result;
}
function hex2bin($data)
{
$len = strlen($data);
return pack("H" . $len, $data);
}
To be short: Your code is correct. You can't test your encryption with provided tools.
Both tools do not allow to enter your IV.
The IV should be unique and can be transferred publicly.
Using wrong IV by decoding gives you wrong part at the beginning of decrypted data.
Here is OO version. It uses zero padding (built in PHP), like your code. It also makes no padding **, if the original message is already aligned.
<?php
$key = "12AB12AB12AB12AB12AB12AB";
$iv = "12AB12AB";
// MESSAGE
$message = "email=billysmith#afakeemail.com&account=987654321&role=22";
echo 'Message::: ' . $message . PHP_EOL;
$cryptor = new Crypt3Des();
$encryptedMessage = $cryptor->encrypt($message, $key, $iv);
echo 'Encrypted::: ' . bin2hex($encryptedMessage) . PHP_EOL;
$decryptedMessage = $cryptor->decrypt($encryptedMessage, $key, $iv);
echo 'Decrypted::: ' . $decryptedMessage . PHP_EOL;
class Crypt3Des
{
private $cipher;
public function __construct()
{
$this->cipher = mcrypt_module_open(MCRYPT_3DES, '', 'cbc', '');
}
public function encrypt($data, $key, $iv)
{
mcrypt_generic_init($this->cipher, $key, $iv);
$result = mcrypt_generic($this->cipher, $data);
mcrypt_generic_deinit($this->cipher);
return $result;
}
public function decrypt($encryptedData, $key, $iv)
{
mcrypt_generic_init($this->cipher, $key, $iv);
$result = mdecrypt_generic($this->cipher, $encryptedData);
mcrypt_generic_deinit($this->cipher);
$result = rtrim($result, "\0");
return $result;
}
}
// Before 5.4.0
if (!function_exists('hex2bin')) {
function hex2bin($data)
{
$len = strlen($data);
return pack("H" . $len, $data);
}
}

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