.NET Encryption/Decryption Problem -- Pls help

From: FOB (fob_in_states@yahoo.com)
Date: 08/26/02


From: "FOB" <fob_in_states@yahoo.com>
Date: Sun, 25 Aug 2002 19:19:31 -0400


Hello geeks,
I am working on some server side infrastructure where I need to encrypt some
data and send it to the client so that the client could send that data back
to me for identification purposes. I am trying to use .NET cryptography
classes but I am running into some problem. Probably problem is with
DESCryptoServiceProvider or I am not able to accurately convert from string
to byte array and vice vera.

At the end, I dont receive the actual string that I encrypted, rather the
string is truncated, means loss of data. If I encrypt the string
"01234567890123456789", I receive only "01234567" !!!!

I would greatly appreciate if someone could point out the problem.

Following is the code that I am using:

private void button1_Click(object sender, System.EventArgs e)
{
 Byte[] arrKey ;
 arrKey = GetByteArray(txtKeyPassword.Text) ;

 Byte[] arrIV ;
 arrIV = GetByteArray(txtIVPassword.Text) ;

 // Data to encrypt
 string strData = "01234567890123456789" ;

 // Convert string data to byte array
 System.Text.UTF8Encoding objEncoding = new System.Text.UTF8Encoding() ;
 Byte[] arrUTF8 = objEncoding.GetBytes(strData) ;

 // Encrypt byte array
 DESCryptoServiceProvider objDES = new DESCryptoServiceProvider() ;
 MemoryStream objMemoryStream = new MemoryStream() ;
 CryptoStream objCryptoStream = new CryptoStream( objMemoryStream,
        objDES.CreateEncryptor(arrKey, arrIV),
        CryptoStreamMode.Write) ;
 objCryptoStream.Write(arrUTF8, 0, arrUTF8.Length) ;
 objCryptoStream.Flush() ;

 Byte[] arrEncryptedData = objMemoryStream.ToArray() ;
 string strEncryptedData = Convert.ToBase64String(arrEncryptedData) ;

 objCryptoStream.Close() ;
 objMemoryStream.Close() ;

 // Decrypt Data.
 // First conver the user token from Base64 to byte array
 // then decrypt the data.
 Byte[] arrEncryptedData2 = Convert.FromBase64String(strEncryptedData) ;
 objMemoryStream = new MemoryStream() ;
 objCryptoStream = new CryptoStream( objMemoryStream,
      objDES.CreateDecryptor(arrKey, arrIV),
      CryptoStreamMode.Write) ;
 objCryptoStream.Write(arrEncryptedData2, 0, arrEncryptedData2.Length) ;
 objCryptoStream.Flush() ;

 // Get the byte array.
 Byte[] arrDecryptedData = objMemoryStream.ToArray() ;

 // Convert the array to string
 string strDecryptedData = objEncoding.GetString(arrDecryptedData) ;
}

private Byte[] GetByteArray(string r_strData)
{
 Byte[] arrByte = new Byte[r_strData.Length] ;
 Encoding objEncoding = System.Text.Encoding.UTF8 ;
 arrByte = objEncoding.GetBytes(r_strData) ;
 return arrByte ;
}

Thanks,
FOB