About Encryption ...

From: José Pérez Hernández (joseperhe_at_yahoo.com)
Date: 04/14/04


Date: Tue, 13 Apr 2004 20:44:28 -0400

Hi,

I'm testing a Rijndael Symetric Algorithm Implementation to encrypt data.
With that intention, i made use of code that i saw in
http://www.derkeiler.com/Newsgroups/microsoft.public.dotnet.framework.aspnet.security/2003-03/0223.html
that encapsulates very good the process of encryption regardless of the
CryptoGraphic Service, in a class called SymmCrypto.

As you can see in the last chunk of code:

   int i = 0;
   for (i = 0; i < bytOut.Length; i++)
     if (bytOut[i] == 0)
        break;

where byOut is the buffer with the encryption resultant data. The intention
is to trim the finnaly '\0' innecessary bytes.

But the matter is that i must to know where to cut, because the Rijndael
Decryption seems only to allows an amount of data, and produces a data block
of fixed size from which i'm interested just partially ( i do not want the
trailing zeros).

What is the relation between the size of the data block to encript, the key
size, and the size of the result (encrypted data block)?

In simple words.. given a key size, wich must to be the length of the data
to encrypt ?

Here is the code...

 public string EncString(string Source, string Key)
 {
   byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);

   // create a MemoryStream so that the process can be done without I/O
files
   System.IO.MemoryStream ms = new System.IO.MemoryStream();
   byte[] bytKey = GetLegalKey(Key);

   // set the private key
   mobjCryptoService.Key = bytKey;
   mobjCryptoService.IV = bytKey;

   // create an Encryptor from the Provider Service instance
   ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();

   // create Crypto Stream that transforms a stream using the encryption
   CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

   // write out encrypted content into MemoryStream
   cs.Write(bytIn, 0, bytIn.Length);
   cs.FlushFinalBlock();

   // get the output and trim the '\0' bytes
   byte[] bytOut = ms.GetBuffer();
   int i = 0;
   for (i = 0; i < bytOut.Length; i++)
     if (bytOut[i] == 0)
        break;
   // convert into Base64 so that the result can be used in xml
   return System.Convert.ToBase64String(bytOut, 0, i);
 }

Regards, José.