Search code examples
initialization-vectorrijndael

what is wrong in my Rijndael that gives me this?


I'm using the Rijndael classes from .net System.Security to Encrypt my RSA Keys

this is how I set it up:

static Rijndael CreateRijndael (byte[] userID, string password, string pepper)
{
    if (userID == null)
        throw new ArgumentNullException ("userID");
    if (password == null)
        throw new ArgumentNullException ("password");
    if (pepper == null)
        throw new ArgumentNullException ("pepper");
    string passpepper = password + pepper;
    Rijndael Rij = Rijndael.Create ();
    Rij.KeySize = 256;
    Rij.Padding = PaddingMode.ISO10126;
    Rij.Mode = CipherMode.CBC;
    Rfc2898DeriveBytes aesKey = new Rfc2898DeriveBytes (passpepper, userID, 65536);
    Rij.Key = aesKey.GetBytes (Rij.KeySize / 8);
    Rij.GenerateIV ();
    return Rij;
}

and this is what I get:

逫⇾귏䜪춈票칔alue><Modulus>kgOu5EG6vbabnvq6xB+cRmxDL....

Instead of

<RSAKeyValue><Modulus>kgOu5EG6vbabnvq6xB+cRmxDL...

Is it the IV?
If it is the IV shouldn't it jumble the whole text considering I've set the mode to CBC?


Solution

  • As you guessed, it is an initialization vector problem.

    On encryption, you should use a random initialization vector, and send it (or store it, in your case) with the ciphertext. On decryption, you should use the same initialization vector as was used for encryption, not a random one.

    With CBC mode, as you are using here, a wrong initialization vector causes just the first block (i.e. 16 bytes for AES) to be garbage, the rest of the content stays okay. The reason is, that each block after the first one is XOR-ed with the previous' block's ciphertext after decryption (and before encryption), and that doesn't depend on the IV.

    With other modes of operation, you could get a totally garbled plaintext.