Problem with Rpeater  
Author Message
csLearner





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Hi,

Could you spare some time to help me with a small problem

I need to perform encryption and decryption using the DES algorithm.

This is the way I want the program to work :

My form has 4 textboxes -
1) tbPlaintext --- For the user to enter the plaintext
2) tbCiphertext --- For displaying he ciphertext
3) tbKey --- For displaying the key
4) tbIV --- For displaying the Initialization Vector
and 2 buttons -
1) Button1 --- When clicked performs encryption using key form tbKey and the IV from the string - "init vec"
2) Button2 --- When clicked performs decryption using the key in tbKey and the IV "init vec"

The user enters the plaintext -"Hello world" and the key - "qwertyui" and clicks the Button1. The ciphertext appears in the textbox tbCiphertext ("SGVsbG8gd29ybGQ=").
This part works fine.
Now when the user clicks the Button2 , after clearing the text in tbPlaintext, the plaintext "Hello world" should appear in tbPlaintext. But what I get is "U0dWc2JHOGdkMjl5YkdRPQ==". How do you explain that

What should I do to get my original plaintext

The MSDN article "How To: Create an Encryption Library in .NET 1.1" at the following URL helped me with the code-
http://www.hide-link.com/
Is there something I'm still missing

Please help me as soon as possible so I can proceed with my project.

- Sreerag Gopinath P C


PHONE : +919447489699

********************************************************************

The event handlers of Button1 and Button2 are as follows -

---------------------------------------------------------------------------------


/* ENCRYPT USING DES ALGORITHM */

private void button1_Click(object sender, System.EventArgs e)
{
if (tbKey.Text == "")
MessageBox.Show("Enter some key");
else
{
if (tbKey.Text.Length == 8)
{
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.CBC;

byte[] plaintext =

Encoding.ASCII.GetBytes(tbplaintext.Text.ToString());

byte[] key =

Encoding.ASCII.GetBytes(tbKey.Text.Trim());
byte[] IV = Encoding.ASCII.GetBytes("init vec");

des.Key = key;
des.IV = IV;

ICryptoTransform transform =

des.Crea****cryptor(des.Key,des.IV);

MemoryStream memStreamEncryptedData = new

MemoryStream();

memStreamEncryptedData.Write(plaintext,0,plaintext.Length);
CryptoStream encStream = new

CryptoStream(memStreamEncryptedData,transform,CryptoStreamMode.Write);

byte[] ciphertext =

memStreamEncryptedData.ToArray();
tbCiphertext.Text =

Convert.ToBase64String(ciphertext);

string msg = String.Format("KEY : {0}\r\nIV :

{1}",Convert.ToBase64String(key),Convert.ToBase64String(IV));
MessageBox.Show(msg);

// tbKey.Text = Convert.ToBase64String(des.Key); //

The key seems to have changed
// tbIv.Text = Convert.ToBase64String(des.IV); // So

does the Initialization Vector

// stored_key = des.Key; // Storing these for later

retrieval
// stored_IV = des.IV; // does not produce the

expected results either.


encStream.Close();
}
else
{

MessageBox.Show("Key length should have 8

characters");
}
}

}


/* Decrypt DES encrypted text */

private void button2_Click(object sender, System.EventArgs e)
{
try
{
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.CBC;

byte[] ciphertext =

Encoding.ASCII.GetBytes(tbCiphertext.Text);

byte[] key = Encoding.ASCII.GetBytes(tbKey.Text); // Prompts

user to enter the key
// byte[] key = Encoding.ASCII.GetBytes("qwertyui"); // Even

this does not seem to work--Why

byte[] IV = Encoding.ASCII.GetBytes("init vec");
// byte[] IV = Encoding.ASCII.GetBytes(tbIv.Text); // Does

not appear to work either

des.Key = key;
des.IV = IV;

// des.Key = stored_key; // Retrieving the Key and IV form

already stored
// des.IV = stored_IV; // variables does not work either


ICryptoTransform transform =

des.CreateDecryptor(des.Key,des.IV);



MemoryStream memDecryptStream = new MemoryStream();
memDecryptStream.Write(ciphertext,0,ciphertext.Length);
CryptoStream cs_decrypt = new

CryptoStream(memDecryptStream,transform,CryptoStreamMode.Write);


byte[] plaintext = memDecryptStream.ToArray();
tbplaintext.Text = Convert.ToBase64String(plaintext);


cs_decrypt.Close();

}
catch(Exception x)
{
MessageBox.Show(x.Message);
}

}



.NET Development33  
 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

For Encryption:

  1. You are Converting Text to bytes using ASCII while encryption is being done.
  2. Cipher gives to bytes which you convert and show back using Base64 Encoding

For Decryption:

  1. You are Converting Text to bytes using Base64 Encoding while you are going to decrypt it.
  2. Decipher gives to bytes which should be converted to ASCII not Base64 Encoding because it was originally generated form ASCII.

So what you need to do it just change this code in your decryption function:

byte[] plaintext = memDecryptStream.ToArray();
tbplaintext.Text = Convert.ToBase64String(plaintext); //Wrong

tbplaintext.Text = Encoding.ASCII.GetBytes(plaintext);

I hope it'll work like Charm now ;-)

Cheers,



 
 
Sreerag Gopinath





PostPosted: .NET Base Class Library, Problem with Rpeater Top

RizwanSharp, you saved my project.

I thank you from the bottom of my heart for your timely help (which came within 10 minutes after I posted my question. I

never got a reply so fast. Thanks again!)

As you had suggested, the problem arose because I was converting the cipher byte into Base 64 Encoding for display. Then, for

decryption, I was using ASCII encoding for conversion into byte[] (where I should have been using base 64 encoding). Again, I

was using base 64 encoding to display the decrypted byte[] where I should have been using ASCII conversion because I was

converting text to bytes using ASCII to begin with.

The ideas you presented helped me.

Thanks to you , it does work like charm.

The event handler for Button2 click is modified as follows -
/* Decrypt DES encrypted text */

private void button2_Click(object sender, System.EventArgs e)
{
try
{
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.CBC;

/////////////////////////////////////////////////////////////////////////
// byte[] ciphertext = Encoding.ASCII.GetBytes(tbCiphertext.Text); // WRONG
byte[] ciphertext = Convert.FromBase64String(tbCiphertext.Text); // RIGHT

byte[] key = Encoding.ASCII.GetBytes(tbKey.Text); // Prompts

user to enter the key
// byte[] key = Encoding.ASCII.GetBytes("qwertyui"); // Even

this does not seem to work--Why

byte[] IV = Encoding.ASCII.GetBytes("init vec");
// byte[] IV = Encoding.ASCII.GetBytes(tbIv.Text); // Does

not appear to work either

des.Key = key;
des.IV = IV;

// des.Key = stored_key; // Retrieving the Key and IV form

already stored
// des.IV = stored_IV; // variables does not work either


ICryptoTransform transform =

des.CreateDecryptor(des.Key,des.IV);



MemoryStream memDecryptStream = new MemoryStream();
memDecryptStream.Write(ciphertext,0,ciphertext.Length);
CryptoStream cs_decrypt = new

CryptoStream(memDecryptStream,transform,CryptoStreamMode.Write);


byte[] plaintext = memDecryptStream.ToArray();

////////////////////////////////////////////////////////
// tbplaintext.Text = Convert.ToBase64String(plaintext); // WRONG
tbplaintext.Text = Encoding.ASCII.GetString(plaintext); // RIGHT

cs_decrypt.Close();

}
catch(Exception x)
{
MessageBox.Show(x.Message);
}

}



 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

You are always welcome and please mark this post as answered if your problem is solved and you are satisifed. So it may help out others when they have the same problem.

Best Regards and Thank You,



 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Thanks ;-)

 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Tell me one thing, From where did you sent me email I could not understand becuase my blog is not working till the time I created it about a week ago. Can you tell me so I can figure out what's wrong.

Thanks alot :-)



 
 
Sreerag Gopinath





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Hi Rizwan,

I got your email and url from the info you submitted to microsoft.

Hope everything's great now.

By the way, I have 2 questions -

1) I get the following Exception when I try to decrypt data using TripleDES. -

"An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll

Additional information: Specified initialization vector (IV) does not match the block size for this algorithm."

However, encryption works fine.

How do I make things right

The code is as follows -

/* Provides TripleDES encryption and decryption using classes in the .net Framework 1.1 */
public class TripleDES_Cryptography
{
public static string Encrypt(string plaintext, string key, string IV)
{
TripleDES des3 = new TripleDESCryptoServiceProvider();
des3.Mode = CipherMode.CBC;

byte[] by_plaintext = Encoding.ASCII.GetBytes(plaintext); // Convert.FromBase64String(plaintext);
byte[] by_key = Encoding.ASCII.GetBytes(key); // Convert.FromBase64String(key);
byte[] by_IV = Encoding.ASCII.GetBytes(IV); // Convert.FromBase64String(IV);

des3.Key = by_key;
des3.IV = by_IV;

ICryptoTransform Encryptor = des3.Crea****cryptor(des3.Key,des3.IV);

MemoryStream ms = new MemoryStream();
ms.Write(by_plaintext,0,by_plaintext.Length);
CryptoStream cs = new CryptoStream(ms,Encryptor,CryptoStreamMode.Write);

byte[] by_ciphertext = ms.ToArray();
string ciphertext = Convert.ToBase64String( by_ciphertext ); //Encoding.ASCII.GetString(by_ciphertext);

cs.Close();

return ciphertext;

}

public static string Decrypt(string ciphertext, string key, string IV)
{
DES des3 = new DESCryptoServiceProvider();
des3.Mode = CipherMode.CBC;

byte[] by_ciphertext = Convert.FromBase64String(ciphertext);//Encoding.ASCII.GetBytes(ciphertext);
byte[] by_key = Encoding.ASCII.GetBytes(key); // Convert.FromBase64String(key);
byte[] by_IV = Encoding.ASCII.GetBytes(IV); // Convert.FromBase64String(IV);

des3.Key = by_key;
des3.IV = by_IV;

ICryptoTransform Decryptor = des3.CreateDecryptor(des3.Key,des3.IV);

MemoryStream ms = new MemoryStream();
ms.Write(by_ciphertext,0,by_ciphertext.Length);
CryptoStream cs = new CryptoStream(ms,Decryptor,CryptoStreamMode.Write);

byte[] by_plaintext = ms.ToArray();
string plaintext = Encoding.ASCII.GetString(by_plaintext);// Convert.ToBase64String( by_plaintext );

cs.Close();

return plaintext;
}
}

Question No. 2) How can I perform RC2 encryption and decryption in the above fashion

The key size always appears wrong. It seems RC2 works with variable key sizes but how do I exploit the feature


 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Hello Gopinath, Sorry for the delay, I'm coming after seing 50's post and finally here's yours,

Anyhow, the problem is obvious in your code, First of all do this in both Encryption and Decryption Methods:

byte[] by_key = Encoding.ASCII.GetBytes(key); // Convert.FromBase64String(key);
byte[] by_IV = Encoding.ASCII.GetBytes(IV); // Convert.FromBase64String(IV);

byte[] by_key = Convert.FromBase64String(key);
byte[] by_IV = Convert.FromBase64String(IV);

and make sure where you are saving these keys always use Convert.ToBase64String() no ASCII.

It'll work surely ;-) if not then please also post the code where you are saying these keys

Second Question:

I have never used RC2 Encryption, RijndaelManaged is the best class to use in .Net's Symetric encryption so I always use Rijndael (AES Encryption). If you need help in RC2 Iw'll check it what's the problem you can post me the code. But its recommended to use Rijndael with 256 bit key size, 256 block size etc.

What I do is Create a New IV for each message Encryption, so If you encrypt the same string for 1000000 times you'll get different Cipher Text.

Anyhow, that's another matter,

Best Regards,



 
 
Sreerag Gopinath





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Hi again,

I did what you asked me to, but it didn't work. It causes the following Format Exception-

"An unhandled exception of type 'System.FormatException' occurred in Cryptography.exe
Additional information: Invalid length for a Base-64 char array."

But the code I posted works perfectly for DES, Rijndael and RC2(I've solved the problem). I'm using the following procedure for all the above -

ENCRYPTION
----------

1. Use ASCII encoding to get the byte[] from the strings - plaintext, key and IV ( Encoding.ASCII.GetBytes() ).
2. I encrypt the byte[] and
3. Display the ciphertext using Convert.ToBase64String().

DECRYPTION
----------

1. Convert.FromBase64String(ciphertext) to get the byte[] from ciphertext.
2. Decrypt the byte[].
3. Display the plaintext using Encoding.ASCII.GetString().


Please note that I am not storing the key and IV anywhere. The user is asked to enter the key in the textbox tbKey. I use the key string to get the byte[] and initialize the IV as the key itself;
So the user does not explicitly enter the IV -


// The prototype is --- public static string Encrypt(string plaintext, string key, string IV)

tbCiphertext.Text = DES_Cryptography.Encrypt(tbplaintext.Text,tbKey.Text,tbKey.Text); // The Call
// the tbKey.Text is passed as both the Key and IV strings

The ciphertext is displayed in the textbox tbCiphertext. Now the assumption is that the user may save this encrypted text somewhere. He should be able to decrypt the ciphertext at a later time by entering the ciphertext and key (assume he has to remember the key) in the concerned textboxes.

I hope my intent is clear now.

*************************************************************************************************

Also, sometimes I get exceptions relating to invalid block sizes or key lengths or IV length not matching block sizes. How do I eliminate the above embarassing situations in a manner that is transparent to the user (The user is not required to know the correct block sizes. He may only be asked to enter key of correct length.The user must be able to encrypt and decrypt text of any size)


 
 
srikanth varma nampally





PostPosted: .NET Base Class Library, Problem with Rpeater Top

hi,

please give the solution to this code

i written this code in button click event

i am able to do encrypt the message but not descrypt it's giving wrong message

private void button1_Click(object sender, System.EventArgs e)

{

string smsg="The Message to encrypt!";

string senc,sdec;

DESCryptoServiceProvider des=new DESCryptoServiceProvider();

System.Text.Encoding utf=new System.Text.UTF8Encoding();

byte[] key=utf.GetBytes("12345678");

byte[] iv={1,2,3,4,5,6,7,8};

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.Crea****cryptor(key,iv);

{

byte[] bmsg=utf.GetBytes(smsg);

byte[] benc=encryptor.TransformFinalBlock(bmsg,0,bmsg.Length);

senc=System.Convert.ToBase64String(benc);

}

{

byte[] benc=System.Convert.FromBase64String(senc);

byte[] bdec=decryptor.TransformFinalBlock(benc,0,benc.Length);

sdec=utf.GetString(bdec);//here is the problem

}

MessageBox.Show("Message : "+smsg+"\n"+"Encrypted : "+senc+"\n"+"decrypted : "+sdec);

}



 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

See wha you are doing:

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.Crea****cryptor(key,iv);

You are doing encryption 2 times!

it should be like this:

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.CreateDecryptor(key,iv);

I hope it'll work ;-)

Cheers!



 
 
sriaknth varma.n





PostPosted: .NET Base Class Library, Problem with Rpeater Top

thank q very much

it's working



 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

You are welcome! please mark my reply as Answered!

Thank You!

Best regards,



 
 
sriaknth varma.n





PostPosted: .NET Base Class Library, Problem with Rpeater Top

hai,

colud u please help me, i am able to Encrypt the data and i am stroing enrypted data into database, but i am not able to decrypt the data which i retrive from database.

i am using 4 textboxes

1) textbox1,textbox2 and button1 to insert the data into database by encrypted it is working fine

2) textbox3,textbox4 and button2 to retrive data which the id given in textbox3 and the decrypted data should display in texbox4, here the problem

here the connection strings:

static SqlConnection cn=new SqlConnection("Data Source=srikanth;user id=sa;password=;database=mydatabase");

SqlCommand comm;

SqlDataReader dr;

string st;

string smsg,smsg1,senc,sdec;

source code for button1 (it's working fine)

try

{

cn.Open();

smsg=TextBox2.Text;

//string senc,sdec;

DESCryptoServiceProvider des=new DESCryptoServiceProvider();

System.Text.Encoding utf=new System.Text.UTF8Encoding();

byte[] key=utf.GetBytes("12345678");

byte[] iv={1,2,3,4,5,6,7,8};

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.CreateDecryptor(key,iv);

{

byte[] bmsg=utf.GetBytes(smsg);

byte[] benc=encryptor.TransformFinalBlock(bmsg,0,bmsg.Length);

senc=System.Convert.ToBase64String(benc);

}

st="insert into Login values('"+TextBox1.Text+"','"+senc+"')";

comm=new SqlCommand (st,cn);

comm.ExecuteNonQuery();

Response.Write("saved");

}

catch(Exception ex)

{

Response.Write(ex);

}

finally

{

cn.Close();

}

source code for button2

try

{

cn.Open();

st="select *from Login where Login_Id='"+TextBox4.Text+"'";

comm=new SqlCommand(st,cn);

dr=comm.ExecuteReader();

if(dr.Read()==true)

{

TextBox4.Text=dr[0].ToString();

smsg=dr[1].ToString();

}

DESCryptoServiceProvider des=new DESCryptoServiceProvider();

System.Text.Encoding utf=new System.Text.UTF8Encoding();

byte[] key=utf.GetBytes("12345678");

byte[] iv={1,2,3,4,5,6,7,8};

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.CreateDecryptor(key,iv);

{

byte[] bmsg=utf.GetBytes(smsg);

byte[] benc=decryptor.TransformFinalBlock(bmsg1,0,bmsg1.Length);//here the problem

TextBox4.Text=utf.GetString(bdec);

}

}

catch(Exception ex)

{

Response.Write(ex);

}

finally

{

cn.Close();

}

}



 
 
RizwanSharp





PostPosted: .NET Base Class Library, Problem with Rpeater Top

Hello Pproblem is not there as where did you mention it. Problem lies one line above the code you pointed.

Remember you stored the string as encoded in Base64 and you get the Base64 string from the database now you need to get back bytes from Base64 not the UTF:

So See the code below:

source code for button2

try

{

cn.Open();

st="select *from Login where Login_Id='"+TextBox4.Text+"'";

comm=new SqlCommand(st,cn);

dr=comm.ExecuteReader();

if(dr.Read()==true)

{

TextBox4.Text=dr[0].ToString();

smsg=dr[1].ToString();

}

DESCryptoServiceProvider des=new DESCryptoServiceProvider();

System.Text.Encoding utf=new System.Text.UTF8Encoding();

byte[] key=utf.GetBytes("12345678");

byte[] iv={1,2,3,4,5,6,7,8};

ICryptoTransform encryptor=des.Crea****cryptor(key,iv);

ICryptoTransform decryptor=des.CreateDecryptor(key,iv);

{

byte[] bmsg=utf.GetBytes(smsg); // ThisLine is Wrong

byte[] bmsg=//Convert.FromBase64String(smsg); // Replaced

byte[] benc=decryptor.TransformFinalBlock(bmsg1,0,bmsg1.Length);//This line is fine

TextBox4.Text=utf.GetString(bdec);

}

}

catch(Exception ex)

{

Response.Write(ex);

}

finally

{

cn.Close();

}

}

I hope this will work like a Charm now.

Best Regards,