Search code examples
c#.netrijndael

How to convert string key and IV to byte arrays for Rijndael


The documentation says "If you use the following values, then you will get this result".

Block Size: 128 Cipher Mode: CBC Padding Mode: Zeros

Key: BTikvHBatPdAtgT3317QIQqGFY25WpIz

IV: a5Sg4U9m11Mw2tIZ

Value to be encyrpted: 2008-06-02 13:28:45,Statements,1234567,,06/01/2008,06/01/2008,0

And this how the encryption result should look like after all these values are used according the developer guides.

b97f3985245be1065604c5808cebaa2e15813bf938cfaa3c198fd464565c13ced7c91ac6 b68326ce5ed5e81cb7de81acb9fcd1b1636127efbac3203da5bdccea

However, I cannot get this result for some reason, this is the code I used to populate this result but it gives me same characters at first and later on the characters changes as you may see in the result at very bottom of this question.

This is the code and below is the new output:

public static void Main(string[] args)
{
  RijndaelManaged rij = new RijndaelManaged();
  rij.Mode = CipherMode.CBC;
  rij.Padding = PaddingMode.Zeros;
  rij.Key = ASCIIEncoding.UTF8.GetBytes("BTikvHBatPdAtgT3317QIQqGFY25WpIz");
  rij.IV = ASCIIEncoding.UTF8.GetBytes("a5Sg4U9m11Mw2tIZ");
  ICryptoTransform transform = rij.CreateEncryptor();

  byte[] data = Encoding.ASCII.GetBytes("2008-06-02 13:28:45,Statements,1234567,,06/01/2008,06/01/2008,0");
  byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
  Console.WriteLine(ByteArrayToString(result));
}

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

My output :

b97f3985245be1065604c5808cebaa2e15813bf938cfaa3c198fd464565c13ced7c91ac6b68326ce5ed5e81cb7de81ac

Note: I needed to update the question as I advanced and found a better solution but the new problem has arose right now.


Solution

  • You were talking about weird characters in your output - actually, the output you posted is hex encoding, so you should try to encode yours to hex, too, as explained here.

    Edit:

    I figured it out now. You need to additionally Close() either the stream or the writer - in CBC mode, this is needed to finalize the padding on the last block, if it is omitted then the last block will not be output. Next problem is that if you do this, then you will still end up with a slightly different output than the one expected in your example. Here's why: if you decrypt your example ciphertext, you will get:

    2008-06-02 13:28:45,Statements,1234567,,06/01/2007,06/01/2007,0
    

    It differs from your plaintext in that there's a 2007 at the end where you have 2008. If you fix this and properly close the stream then you will finally receive exactly the same output as in the example.