kamaz08
kamaz08

Reputation: 21

Creating compatible AES-256-CBC code in C# and as an OpenSSL command

I have problem with encoding using OpenSSL in Linux terminal and .net Cryptography in C#.

When I use:

openssl enc -A -aes-256-cbc -base64 -K b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe -iv e43f2a549d05132fe2efe555edbd42a0 <<< "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to..."

which returns

+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZa/MhqBICBW0kagAcSy6Y6g==

My C# code is:

public static byte[] GetByteArrayFromStringHex(string HexString)
{
    int NumberChars = HexString.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
    return bytes;
}
public static void EncryptTest()
{
    string key = "b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe";
    string iv = "e43f2a549d05132fe2efe555edbd42a0";
    string mess = "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to...";
    RijndaelManaged myAes = new RijndaelManaged();
    myAes.KeySize = 256;
    myAes.BlockSize = 128;
    myAes.Padding = PaddingMode.PKCS7;
    myAes.Mode = CipherMode.CBC;
    var enrypt = myAes.CreateEncryptor(GetByteArrayFromStringHex(key), GetByteArrayFromStringHex(iv));
    byte[] byteInput = Encoding.UTF8.GetBytes(mess);
    DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
    var memStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memStream, enrypt, CryptoStreamMode.Write);
    cryptoStream.Write(byteInput, 0, byteInput.Length);
    cryptoStream.FlushFinalBlock();
    Console.WriteLine(Convert.ToBase64String(memStream.ToArray()));
}

which returns

+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZVM7jph3JF0gic6VECmsZ2w==

Why does it return two different ciphertexts?

Upvotes: 0

Views: 905

Answers (1)

oliv
oliv

Reputation: 13239

The output of both encryptions is different because the shell you use (bash, ksh...) is adding a trailing newline to the string when using the here string functionality <<< (reference here).

To have the exact same encryption use printf:

printf "%s" "Ala ma kota. Kot ma, ale... to jednak ona go posiada. Jednakże gdy przeczytamy to ponownie to..." | openssl enc -aes-256-cbc -base64 -A -K b14f636c88ba3dad57d53a8fab09dd95512ce1b545bbb93362113487e73a13fe -iv e43f2a549d05132fe2efe555edbd42a0
+xD6VmtDUqiwpGsOYDNajofvMdS8F1eYkK50l+dsuqdgr6bUf2xWSwdEifd96A5h/yM2bIxdWeWM5+4eCCitDjh+qZDj32rJS0fpV/q08hhfNltWdWxJhVezcuIAV3VZVM7jph3JF0gic6VECmsZ2w==

Upvotes: 3

Related Questions