[Mono-dev] Question about TransformFinalBlock with SymmetricAlgorithms and CBC

Sebastien Pouliot sebastien.pouliot at gmail.com
Fri Jan 30 13:08:53 EST 2009


On Fri, 2009-01-30 at 12:27 -0500, David Wolinsky wrote:
> Hey guys,
> 
> Just wanted to let you know a behavioral difference between .Net and 
> Mono and potentially get advice from you.  The method 
> SA.CreateEncryptor.TransformFinalBlock() differs on the two platforms.  
> Specifically, Mono appears to continue from where the last one ended, 
> whereas .Net repeats itself (i.e. the IV is the same IV you inserted 
> when the ICryptoTransform was created).
> 
> Below is a sample.
> 
> using System;
> using System.Security.Cryptography;
> 
> public class tdes_test {
>   public static void Main() {
>     RijndaelManaged rm = new RijndaelManaged();
>     byte[] key = new byte[rm.KeySize / 8];
>     for(int i = 0; i < key.Length; i++) {
>       key[i] = (byte) i;
>     }
>     byte[] iv = new byte[rm.BlockSize / 8];
>     for(int i = 0; i < iv.Length; i++) {
>       iv[i] = (byte) i;
>     }
>     ICryptoTransform encryptor = rm.CreateEncryptor(key, iv);
>     byte[] data = new byte[111];
>     for(int i = 0; i < data.Length; i++) {
>       data[i] = (byte) i;
>     }
> 
>     byte[] encrypted_data = encryptor.TransformFinalBlock(data, 0, 
> data.Length);
>     for(int i = 0; i < encrypted_data.Length; i++) {
>       Console.Write(encrypted_data[i]);
>     }
>     Console.WriteLine("\n");
>     encrypted_data = encryptor.TransformFinalBlock(data, 0, data.Length);
>     for(int i = 0; i < encrypted_data.Length; i++) {
>       Console.Write(encrypted_data[i]);
>     }
>   }
> }
> 
> 
> We're currently using this on a datagram security system and on Mono 
> (not sure if .Net is the same) creation of Encryptors and Decryptors is 
> expensive.  Any thoughts or suggestions?

Your code should always* look at ICryptoTransform.CanReuseTransform
before reusing a transform. If false then it cannot be reused.

* since you should be using the factory methods to create ciphers
(e.g. Rijndael.Create) and you can't be sure what exact class the
runtime will instantiate (nor it's behavior).

Sebastien



More information about the Mono-devel-list mailing list