Click here to Skip to main content
15,895,777 members
Articles / Programming Languages / C#
Tip/Trick

How to encrypt or decrypt your application's password

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
24 May 2013CPOL 17.1K   156   7   3
Using this code, you can encrypt the plain text and stored into database and again decrypt the password.

Introduction    

I have used some predefined value for this encryption. You can change the value for your own purpose.

Background 

Anyone who has knowledge about C# can understand the coding. The application was developed with Visual Studio 2010. 

Using the code 

I have set some predefined value in the form load event. 

C#
private void Form1_Load(object sender, EventArgs e)
{
    txtPassPhrase.Text = "Pas5pr@seDbblIT";           // can be any string
    txtSaltValue.Text = "s@1tValueDbblIT";            // can be any string
    txtHashAlgorithm.Text = "SHA1";
    txtPasswordIterations.Text = Convert.ToString(5); // can be any number
    txtInitVector.Text = "@1B2c3D4e5F6g7H8";          // must be 16 bytes
    txtKeySize.Text = Convert.ToString(256);
}  

I have placed a TextBox in where the plain text input will be. 2 button namely Encrypt and Decrypt, 2 label for output the encrypt and decrypt value.  

Clicking the Encrypt button following code will execute and display the encrypted value into lblEncryptText label.

There is a global variable which will store the cipher text for later decryption.

C#
string encryptedCipherText = "";

private void btnEncrypt_Click(object sender, EventArgs e)
{ 
    string plainText = txtPlainText.Text;
    string passPhrase = txtPassPhrase.Text;        
    string saltValue = txtSaltValue.Text;        
    string hashAlgorithm = txtHashAlgorithm.Text;             
    int passwordIterations = Convert.ToInt32(txtPasswordIterations.Text);
    string initVector = txtInitVector.Text; 
    int keySize = Convert.ToInt32(txtKeySize.Text);
    string cipherText = EncryptVal(plainText, passPhrase, saltValue, 
           hashAlgorithm, passwordIterations, initVector, keySize);
    encryptedCipherText = cipherText;
    lblEncryptText.Text = "Encrypted :  " + cipherText;
}  

EncryptVal( ) method will encrypt the plain text based on the passed parameter.

C#
private string EncryptVal(string plainText, string passPhrase, 
    string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
    byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, 
                        saltValueBytes, hashAlgorithm, passwordIterations);
    byte[] keyBytes = password.GetBytes(keySize / 8);
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
    cryptoStream.FlushFinalBlock();
    byte[] cipherTextBytes = memoryStream.ToArray();
    memoryStream.Close();
    cryptoStream.Close();
    string cipherText = Convert.ToBase64String(cipherTextBytes);
    return cipherText;
} 

Clicking on Decrypt button, takes the cipher text and other parameters to decrypt into plain text.

C#
private void btnDecrypt_Click(object sender, EventArgs e)
{
    string cipherText = encryptedCipherText;
    string passPhrase = txtPassPhrase.Text;
    string saltValue = txtSaltValue.Text;
    string hashAlgorithm = txtHashAlgorithm.Text;
    int passwordIterations = Convert.ToInt32(txtPasswordIterations.Text);
    string initVector = txtInitVector.Text; 
    int keySize = Convert.ToInt32(txtKeySize.Text);
    string plainText = DecryptVal(cipherText, passPhrase, saltValue, 
       hashAlgorithm, passwordIterations, initVector, keySize);
    lblDecryptText.Text = "Decrypted : " + plainText;
}  

DecryptVal( ) method will decrypt the cipher text based on the passed parameter. 

C#
private string DecryptVal(string cipherText, string passPhrase, 
  string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
    byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
    byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
    byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
    PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, 
      saltValueBytes, hashAlgorithm, passwordIterations);
    byte[] keyBytes = password.GetBytes(keySize / 8);
    RijndaelManaged symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
    MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    memoryStream.Close();
    cryptoStream.Close();
    string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    return plainText;
}  

 Source Code for this article:   https://www.dropbox.com/s/ctwn1n461i0i5e2/EncryptDecrypt.rar  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Dutch-Bangla Bank Ltd.
Bangladesh Bangladesh
I am Sk. Razibul Islam. Completed B.Sc.(CSE) from Khulna University, MBA(Finance) from Southeast University, Bangladesh.
Currently working as Software Engineer(Executive Officer) at Dutch-Bangla Bank. Earlier I was at SentranaBD (An Offshore Company of Sentrana Inc, USA) as Member Engineering(L-2), and was Assistant Manager(IT) at Beximco Textiles Ltd. I have been working in Java, C#, ASP.NET for the last 9 years. Also possess knowledge in J2SE for Web Development (Member programmer of www.sensiblematch.com).

Comments and Discussions

 
QuestionTnks Pin
mexicali8214-Jun-13 6:04
mexicali8214-Jun-13 6:04 
GeneralMy vote of 1 Pin
OriginalGriff24-May-13 21:05
mveOriginalGriff24-May-13 21:05 
QuestionThe problem I have with this Pin
OriginalGriff24-May-13 21:04
mveOriginalGriff24-May-13 21:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.