Getting my bash OpenSSL to replicate C# code

Viewed 51

I'm trying to decrpyt a base64 encoded string in bash using openSSL. I have the password, and I have C# code that works (very new to C#, and luckily found dotnetfiddle - so have got it working in C#) -- and I thought it would be easy to do this in openSSL. I think I'm probably not understanding some key implicit options that C#'s CryptoStream() function uses.

So in C# to decrypt (successfully) I am using..

byte[] aesKey = Encoding.UTF8.GetBytes("MYPASSWORD123");
aesAlg.Key = aesKey;  
aesAlg.IV = aesKey;  
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
   using (MemoryStream msDecrypt = new MemoryStream(cipherText)) {
       using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
           using (StreamReader srDecrypt = new StreamReader(csDecrypt)) {
                // Read the decrypted bytes from the decrypting stream
                // and place them in a string.
                plaintext = srDecrypt.ReadToEnd();
           }
       }
   }

and that works! (quite a surprise for my 2nd only bit of C#). So I thought easy in bash....

cat /tmp/encrypted | base64 -d > /tmp/foo

openssl enc -d -aes-256-cbc -k "MYPASSWORD123" -in /tmp/foo -out /tmp/foo2

also tried converting password and IV to hex and using...

openssl enc -d -aes-256-cbc -K "$hex" -iv "$hex" -in /tmp/foo -out /tmp/foo2

also tried...

openssl enc -d -base64 -aes-256-cbc -K "MYPASSWORD123" -iv "MYPASSWORD123" -in /tmp/encrypted -out /tmp/foo2

I get hex string is too short, padding with zero bytes to length, bad decrypt and bad magic number. I am using openSSL 1.1.1, and have tried -salt and -md md5 options. I but stumped here - would appreciate any insights - many thanks

1 Answers

Have fixed it. Some help from https://www.devglan.com/online-tools/aes-encryption-decryption

So it seens the C# function is smart enough (as i wasn't) to work out that a short 16 digit password means I should be using the aes-128-cbc algo rather than 256. (don't get me started on why they aren't using 256 or using password same as IV... legacy systems).

So I get a perfect result with:

cat /tmp/foo | base64 -d | openssl enc -d -aes-128-cbc -K $hex -iv $hex

but 90% lost and only get the last few lines with...

openssl enc -d -base64 -aes-128-cbc -K $hex -iv $hex -in /tmp/foo

(which I don't understand, and the 2nd option would be neater, but hey who has the time?)

Related