Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This article helps the C# beginners to do simple encryption and decryption of strings. It will be useful for simple password encryption or any such string encryption.

Encryption using the default key:

Encryption1.jpg

Encryption using the user's custom key:

Encryption.jpg

Decryption using the user's custom key:

Using the Code

The demo application uses a class SSTCryptographer which contains two static overloaded methods and a static property. 

How To Use the Given Code

On Button clicks:

private void btnEncrypt_Click(object sender, EventArgs e)
{ 
txtOutputText.Text = SSTCryptographer.Encrypt(txtInputText.Text,SetKey());
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
txtOutputText.Text = SSTCryptographer.Decrypt(txtInputText.Text,SetKey());
}

/// <summary>
/// Encrypt the given string using the default key.
/// </summary>
/// <param name="strToEncrypt">The string to be encrypted.</param>
/// <returns>The encrypted string.</returns>
public static string Encrypt(string strToEncrypt)
{
    try
    {
        return Encrypt(strToEncrypt, _key);
    }

    catch (Exception ex)
    {
        return "Wrong Input. " + ex.Message;
    }
} 

/// <summary>
/// Decrypt the given string using the default key.
/// </summary>
/// <param name="strEncrypted">The string to be decrypted.</param>
/// <returns>The decrypted string.</returns>
public static string Decrypt(string strEncrypted)
{
    try
    {
        return Decrypt(strEncrypted, _key);
    }
    catch (Exception ex)
    {
        return "Wrong Input. " + ex.Message;
    }
}

/// <summary>
/// Encrypt the given string using the specified key.
/// </summary>
/// <param name="strToEncrypt">The string to be encrypted.</param>
/// <param name="strKey">The encryption key.</param>
/// <returns>The encrypted string.</returns>
public static string Encrypt(string strToEncrypt, string strKey)
{
    try
    {
        TripleDESCryptoServiceProvider objDESCrypto = 
			new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
        byte[] byteHash, byteBuff;
        string strTempKey = strKey;
        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
        byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
        return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
			TransformFinalBlock(byteBuff, 0, byteBuff.Length));
    }
    catch (Exception ex)
    {
        return "Wrong Input. " + ex.Message;
    }
}

/// <summary>
/// Decrypt the given string using the specified key.
/// </summary>
/// <param name="strEncrypted">The string to be decrypted.</param>
/// <param name="strKey">The decryption key.</param>
/// <returns>The decrypted string.</returns>
public static string Decrypt(string strEncrypted, string strKey)
{
    try
    {
        TripleDESCryptoServiceProvider objDESCrypto = 
			new TripleDESCryptoServiceProvider();
        MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
        byte[] byteHash, byteBuff;
        string strTempKey = strKey;
        byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
        objHashMD5 = null;
        objDESCrypto.Key = byteHash;
        objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
        byteBuff = Convert.FromBase64String(strEncrypted);
        string strDecrypted = ASCIIEncoding.ASCII.GetString
		(objDESCrypto.CreateDecryptor().TransformFinalBlock
		(byteBuff, 0, byteBuff.Length));
        objDESCrypto = null;
        return strDecrypted;
    }
    catch (Exception ex)
    {
        return "Wrong Input. " + ex.Message;
    }
}
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralThanks
Mushtaque Nizamani
21:20 7 May '09  
Hi Lovely Manuel,
Thanks for the nice article.

Regards,
Mushtaque Nizamani

GeneralRe: Thanks
Lovely M
22:48 7 May '09  
Welcome Mushtaque Nizamani...

Lovely Manuel
Santhisoft Technologies

Questionqusetuion
marzieh minooyee
21:41 19 Dec '08  
hi , that nice code, but when i want decrypt a text , i give the error ,this my error:
Wrong Input. Invalid character in a Base-64 string.
i want encrypt a long text and decrypt it. Frown Cry
AnswerRe: qusetuion
Lovely M
18:53 21 Dec '08  
hi, you need to cut or copy the decrypted text and paste it into the Input Text textbox. Then click the Decrypt button. Hope that it will help you.

Lovely Manuel
Santhisoft Technologies

GeneralString reference not set to an instance of String
Asanda
2:48 8 Sep '08  
I keep getting this error(String reference not set to an instance of String), when I try to decrypt the password(encrypted with MD5)in the database.

A Koom

GeneralRe: String reference not set to an instance of String
Lovely M
19:37 8 Sep '08  
You need to encrypt your password using the encryption algorithm given in this article to decrypt it with the same. Also the key used to encrypt should be same while decypting it. I think you tried to decrypt your password which is encrypted by some other key.

Lovely Manuel
Santhisoft Technologies

GeneralRe: String reference not set to an instance of String
Asanda
3:46 9 Sep '08  
Thanks. Now it is giving me this error(Bad Data).I'm using the default key.

A Koom

GeneralRe: String reference not set to an instance of String
Lovely M
19:35 9 Sep '08  
Please Try again as I think you are pressing wrong buttons at wrong time.
While decrypting the encrypted text should enter/paste in the input text box and then press the Decrypt button.

Lovely Manuel
Santhisoft Technologies

GeneralThanks! Thank You! And More Thanks!
microbus
12:13 22 Jul '08  
Great article, you have one of the better lessons available for encryption newbs like myself...

Cheers.
GeneralThanks a lot
Abhi suryawanshi
22:35 4 Jul '08  
SmileSmileSmile , its working fine

Windows mobile development, pocket pc development , C#.net compact framework, Desktop application , web service

QuestionInvalid length for a Base-64 char array.
moistllama
5:30 20 Mar '08  
I downloaded the program and no matter what I type I recieve this error
"Wrong Input. Invalid length for a Base-64 char array."
AnswerRe: Invalid length for a Base-64 char array.
Amar Chaudhary
21:34 29 Apr '08  
Please Try again as I think you are pressing wrong buttons at wrong time

It is Good to be Important but!
it is more Important to be Good

GeneralHow to decrypt an encrypted string using MD5 algorithm
Member 2771851
18:58 22 Feb '08  
How can I decrypt an encrypted string using MD5 algorithm
GeneralNice article
Rajib Ahmed
10:13 20 Feb '08  
5 from me. Maybe a little bit more comments though.

Rajib Ahmed

GeneralRe: Nice article [modified]
Lovely M
10:55 20 Feb '08  
Thank you.

Lovely Manuel
Santhisoft Technologies

Website Template, Simple POS Software, Personal Accounting Software, Video Rental Software, Tutorials - C#.Net, VC++, VB.Net


Last Updated 21 Feb 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010