How to encrypt a string using c#

The following cose sample shows how to encrypt a string using c#
private string encryptString(string strToEncrypt)
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);

// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvi der md5 = new System.Security.Cryptography.MD5CryptoServiceProvi der();
byte[] hashBytes = md5.ComputeHash(bytes);

// Convert the encrypted bytes back to a string (base 16)
string hashString = "";

for(int i=0;i{
hashString += Convert.ToString(hashBytes[i],16).PadLeft(2,'0');

return hashString.PadLeft(32,'0');


Author: Kapil Dhawan17 Jun 2008 Member Level: Gold   Points : 2

Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code will help lots of guys
Thanks to you

Author: Jelte Verbree19 Sep 2008 Member Level: Bronze   Points : 2


Great code it was very useful to me, but I think that here is missing something in this code

for(int i=0;i
hashString += Convert.ToString(hashBytes[i],16).PadLeft(2,'0');

return hashString.PadLeft(32,'0');

does it have to be something like this?

for(int i=0; ...missing... ; i++)

Correct me if i'm wrong ;)

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: