Getting extra garbage with AES 256 decrypt (php, phpseclilb, openssl) - php

I have the following PHP code:
require('/var/www/third_party_plugins/phpseclib/vendor/autoload.php');
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
use phpseclib3\Math\BigInteger;
use phpseclib3\Crypt\AES;
use phpseclib3\Crypt\Random;
$message = hex2bin('f5f905e8b2d8f0a72e179a169a59bc373021a75865e55c6797627bc43ddc6af0d9bd673bf94f5e8defc5af81019fd87c7d504a6aa758ba1e2f1f9858d0293b0b');
$key = hex2bin('d2ce45fd5f80c15db0a4ab26a7e27f42b507ed9469f0d63c1dbe4f89ed84c0c2');
$iv = hex2bin('db9d7e844b00282327221bb563639f96');
$cipher = new AES('cbc');
$cipher->setIV($iv);
$cipher->setKey($key);
//$cipher->disablePadding();
$Decrypted = bin2hex($cipher->decrypt($message));
print("\n" . $Decrypted . "\n");
When I run this code, I get the following result:
240dcbefc0f82fadc00ef8494488aaa81400000c2def01e79fec6c4d9a822358dd8a910cac606e8afcb607793cb442093a56b7b40b
Inside of this result, I can see the message I WANT, which is:
1400000c2def01e79fec6c4d9a822358
However, there are 16 bytes of data in the front of the message which make no sense to me, it seems like some kind of padding, but I dont want it in my result nor do I understand why it is there, because from what I understand the padding should be removed by phpseclib or openssl functions
240dcbef c0f82fad c00ef849 4488aaa8
I understand that there is a 20 byte MAC at the end, however, I notice ONE extra byte in front of the mac:
dd8a910cac606e8afcb607793cb442093a56b7b40b // THIS IS 21 BYTES, NOT 20...why?
I'm also having trouble re-encrypting the data and getting a valid response from the server, as I'm re-encrypting it with PHP, then sending the SAME data to my C# server, and it is unable to decrypt the message.

Related

openssl_decrypt for aes-128-cbc not working

I am working on decrypting some content coming from an API. They have provided a command as well. So with some mofication below is the command, which works perfectly fine:
openssl enc -d -aes-128-cbc -K 422943374a3568755d7c527f6e472132 -iv 00000000000000000000000000000000 -nopad -in <(echo 'D5fiXKI4ie4c69gcCwM4/p414yrYtH9np+piNoqZASbkUnHAvbB4norHz6d6uzJmIg1sULhHFmfQTkvpw0tIEVmNcjyP6j2LK8zXYzohtNlsqBHx5v4xHEIyCcvfbMJddd5hs97jqkUtHuQyer2GdfDKZseaGgpXJ75GK7uKFPkbJ3wgQ6A0Q7q2tbBYeXEDmRMO6OhWeHgrezQOcyjcdOQk50SjMuaSb9IRimwagXamiXRg0LyTzA18a0SuqtbKCNgXnmhf39YxJUudkRmcMQ==' | base64 --decode)
I need to code in PHP, so I need to translate same thing in PHP, and here is what I have written in PHP:
$encodedStr = "PYroeIibeYwy/waD3opLw6yWT6Wfv3AhBKhQpoR+6qT9gx/bTDdR9QIfXcVURoQ2QlTl8L+JZX4Ije8M+FAQOxVmEXAmyUpzLgeg7aRCA6iiJbav/W3xW0BWb3D3QELjKTN4KRB2FdM7G5eIIfvjpeySLxQ3h7eL16nQf+1rms4VoVsBaeO8aU+Zy9saKZR4oL+k40m6tjtvtXryg7sWcmUgdonP/Jg4osESrY3MmGl7qXSpJC+v4g3iOY7s8NwywSN9q2Id7P0IaVtb5AFOEQ==";
$secretHash = ",MF-,2Y*s8DoYCFI";
$encryptionMethod = "AES-128-CBC";
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
$encrypted = base64_decode($encodedStr);
$hexKey = strToHex($secretHash);
$response = openssl_decrypt($encodedStr, $encryptionMethod, $hexKey, OPENSSL_ZERO_PADDING, $iv);
And in response, I am getting a string of odd characters instead of actual string which I can get from openssl command in command line.
As per openssl_decrypt documentation:
Takes a raw or base64 encoded string and decrypts it using a given method and key.
I have also tried giving base64 decoded value as well in first argument of this function. Encryption method also seems fine. And Zero padding as told in API document. Only thing which I think can be doubtful is zero iv. Let me know if I am making zero iv in wrong way. I have tried not using iv as well but not useful. Or also let me know if I am doing wrong in something else.
openssl_decrypt expects key to be binary not hex. You don't need to convert $secretHash to hex and just pass it as is.
$response = openssl_decrypt($encodedStr, $encryptionMethod, $secretHash, OPENSSL_ZERO_PADDING, $iv);

Encrypt Decrypt Python PHP convert AES

I have this issue where something is encrypted in python using aes 256 cbc encryption as shown in the python codes encrypt method .
I am trying to create a Decrypt method in php to actually decrypt whats encrypted using the python class .
Here is my attempt to convert the python decryption method to php does it look right or am I missing something in my conversion as every time i use the php version to decrypt it says hmac failed ?
anyhelp in converting the python class to php i will appreciate.
public function decrypt(){
$encrypt_method ="AES-256-CBC";
$secret_key =base64_decode('samekeyusedintheencryption');
$encrypted=(string)'some encrypted text to be decrypted';
$data=json_decode(base64_decode($encrypted),true);
$secret_iv =base64_decode($data['iv']);
$output = \openssl_decrypt($data['value'],
$encrypt_method,$secret_key,0,$secret_iv);
return json_encode($output);
}
def decrypt(self, payload):
data = json_c.decode(base64.b64decode(payload))
value = base64.b64decode(data['value'])
iv = base64.b64decode(data['iv'])
crypt_object=AES.new(self.key,AES.MODE_CBC,iv)
plaintext = crypt_object.decrypt(value)
return loads(plaintext)
OK, I got it to work!
function decrypt($encryptedText, $secret_key){
$secret_key = base64_decode($secret_key);
$encrypt_method ="AES-256-CBC";
$data = json_decode(base64_decode($encryptedText),true);
$data['iv'] = base64_decode($data['iv']);
$data['value'] = base64_decode($data['value']);
return openssl_decrypt($data['value'], $encrypt_method, $secret_key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $data['iv']);
}
Some things I learned:
If the options in the openssl function are set to '0' it expects a base64_encoded input for the cipher text. Also, if the default options is set to '0' the padding default is set to PKCS#7. This, I think, is why we were getting the bad block size error.
So, the cipher text needs to be base64_decoded and we need to set both options for the padding.
I was able to decrypt your provided cipher text and see the email addresses.
You are provided the MAC in the Data array so this would allow you to check the MAC in the PHP script. This allows you to make sure the data has not been tampered with.
I recently did an encryption project and started with the open ssl, but ended up changing to the libSodium library. I highly recommend you check it out for any further projects.
Cheers!

AES encrypt in Terminal and decrypt in PHP

I have come accross other threads with similar questions but due to recent changes in PHP (ie. mcrypt removal), I am seeking some advice as to how I'd best go about this using OpenSSL in 2017/18.
Using echo 'this string will be encrypted' | openssl enc -aes-256-cbc -a -pass pass:123 in the Mac Terminal, I was able to password encrypt the string and would now like to pass this (as a parameter) into a server-side PHP function to decrypt.
Having studied this question, I can see that it is possible but it uses the now removed mcrypt function. Further reading in the PHP manual, I am no closer to figuring out how to reverse this encryption command into its PHP decryption equivalent.
This recent answer is what I have implemented so far, yet again, it just won't work with a Terminal generated encryption, only one which was created in PHP (not shown here).
<?php
$encrypted_string = $_GET['data'];
$password = '123';
$decrypted_data = openssl_decrypt($encrypted_string, "AES-256-CBC", $password);
print "Decrypted Data: <$decrypted_data>\n";
?>
The OpenSSL PHP manual states that either plain text or base64 encoded strings can be passed in and be decrypted. As I have used the -a flag during encryption, I would expect base64 to be passed in, thus eliminating the source as a potential reason why no decrypted data is returned.
I have taken care of URL encoding such that any + symbols produced by the encryption algorithm are replaced with their - %2B - URL-Safe equivalent as they would otherwise be turned into a space character, thus breaking the parameter string. This further ensures that the encoded input string is correctly addressed by the decryption algorithm.
Questions: Why won't my PHP function decrypt the string generated by the terminal command, although both use the same method and password? What is missing from my PHP code that would enable this to work?
Cheers everyone.
UPDATE
I am now using Terminal command:
echo 'blah' | openssl enc -aes-256-cbc -a -K B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF -iv 64299685b2cc8da5
which encrypts to: Y4xelTtEJPUHytB5ARwUHQ==
I pass this to PHP using www.example.com/?data=Y4xelTtEJPUHytB5ARwUHQ==
PHP should take data param and decrypt. Currently, that function looks like this:
<?php
$encrypted_string = base64_decode($_GET['data']);
$key = 'B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF';
$iv = '64299685b2cc8da5';
$output = openssl_decrypt($encrypted_string, 'AES-256-CBC', hex2bin($key), OPENSSL_RAW_DATA, hex2bin($iv));
print "Decrypted Data: <$output>\n";
?>
OpenSSL uses a proprietary KDF that you probably don't want to put the effort in to reproduce in PHP code. However, you can pass your key as pure hex instead, avoiding the KDF, by using the -K flag:
echo 'blah' | openssl enc -aes-256-cbc -K 0000000000000000000000000000000000000000000000000000000000000000
Here, the large hex string is your 256-bit key, hex encoded. This encryption operation will be compatible with your PHP.

AES-256-CBC Encryption/Decryption hex string using openssl in php

I'm a noob developer and I'm trying to decrypt some data but when I use OpenSSL in PHP I received no response. Also, when trying to encrypt data OpenSSL add a block of characters.
This is the code:
<?php
$dataToDecrypt = hex2bin("C2E5CDFE8BBFBC7350D40538434824DD3E11520B89A5BFDE24FA064DB2EED6EA");
$aesKey = hex2bin("E3FB8EA130722FA99266B96B77C2735C39393939393939393920202020202020");
$iv = hex2bin("00000000000000000000000000000000");
$result = openssl_decrypt($dataToDecrypt, 'AES-256-CBC', $aesKey, OPENSSL_RAW_DATA, $iv);
echo bin2hex($result);
?>
The $result is supposed to be:
C3A6149C73FFBE4EAD36DC62FE40877D17CD690F37B06058CA3D65A345CC8212
I've tried this on VB and even in a AES encription web page (http://aes.online-domain-tools.com/) and the result is correct. But when trying with PHP I've got no answer.
I noticed when encrypting with the same information, the encrypted data is different. This is the code:
<?php
$dataToEncrypt = hex2bin("C3A6149C73FFBE4EAD36DC62FE40877D17CD690F37B06058CA3D65A345CC8212");
$aesKey = hex2bin("E3FB8EA130722FA99266B96B77C2735C39393939393939393920202020202020");
$iv = hex2bin("00000000000000000000000000000000");
$result = openssl_encrypt($dataToEncrypt, 'AES-256-CBC', $aesKey, OPENSSL_RAW_DATA, $iv);
echo bin2hex($result);
?>
When I encrypt the result is:
C2E5CDFE8BBFBC7350D40538434824DD3E11520B89A5BFDE24FA064DB2EED6EA3A3ED407DC78D6AF9030BAB90CB40EAD
I get 32 characters more than expected (3A3ED407DC78D6AF9030BAB90CB40EAD). When I encrypt in VB or using the web page mentioned before I don't get these 32 extra characters.
Why is this happening? Am I missing something? I've been searching for an answer for several days. Any help is appreciated.
To see something during PHP decrypt you need to turn on warning messages.
Essentially the openssl_decrypt call will first decrypt your ciphertext. As long as your ciphertext is a multiple of 16 bytes (the block size of AES) this will always succeed. After that it will try and perform PKCS#7 compatible unpadding, which will fail (with high probability). To make it not unpad, use the OPENSSL_ZERO_PADDING in addition to OPENSSL_RAW_DATA.
The same goes for your encryption function of course. Currently you receive the ciphertext of the padded plaintext. This will add exactly one block of padding if the input plaintext is a multiple of the block size (and it is in your sample code). So you need OPENSSL_ZERO_PADDING there as well.

Openssl encrypted in PHP needs to be decrypted in Ruby

In our application we are getting encrypted text from external server. This text have been encrypted using openssl in php.
When I am trying to decrypt the text in my Ruby code, I am getting following error message:
OpenSSL::Cipher::CipherError: wrong final block length
I read couple of solutions on Stackoverflow and was suggest to add following line to the code cipher.padding = 0. But after adding padding = 0, I am getting different error:
OpenSSL::Cipher::CipherError: data not multiple of block length
Below is my rough script I have written to decrypt the code.
require 'openssl'
require 'digest/sha1'
require 'base64'
encrypted = "VaZYJzn9QVEQIH4fmtA1Cg=="
key = "my_secret_key"
cipher = OpenSSL::Cipher::Cipher.new("aes-128-ecb")
cipher.decrypt
cipher.padding = 0
cipher.key = key
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts Base64.decode64(decrypted)
If I encrypt the text using Ruby then I can easily decrypt it. I am having problem to decrypt the code which are encrypted in php. Is there any way I can make encryption and decryption compatible between php and Ruby.
Simply change the way you call it.
From decrypted << cipher.final to decrypted = cipher.update(encrypted) + cipher.final
could get the string like
<GF\x8F\xDC\x91\xE1ew\xB1\x1C\xE8\xF8V\xA0\x99g\x01C\xCDF\xD6\v\x841l\x13\xA6\x9496{
Last, quote from Ruby Doc You should never use ECB mode unless you are absolutely sure that you absolutely need it

Categories