Here in this example, I have explained how to encrypt a password before storing it in a database and secondly, how to decrypt it. In most of the project we need Encrypt and Decrypt of User id and password, so here, I have given a simple example and shown how could we Encrypt and Decrypt our UserId and password.
First take a web form into your project and design the form like the following to enter the Password. Here is how my form will look like:
Following is the HTML view:
- <div>
- <asp:TextBox ID="txt_password" runat="server"></asp:TextBox>
- <asp:Button runat="server" ID="btn_subbmit" Text="ENCRYPT" OnClick="btn_subbmit_Click" />
- <p> </p>
- </div>
- <div>
- <asp:TextBox ID="txt_enpass" runat="server"></asp:TextBox>
- <asp:Button runat="server" ID="btn_decrypt" Text="DECRYPT" OnClick="btn_decrypt_Click" />
- <p> </p>
- </div>
And in the .cs page I have declared the following two methods for encrypting and decrypting the password that user entered.
- public string EncryptPwd(String strString)
- {
-
-
-
-
- int intAscii;
- string strEncryPwd = "";
- for (int intIndex = 0; intIndex < strString.ToString().Length; intIndex++)
- {
- intAscii = (int) char.Parse(strString.ToString().Substring(intIndex, 1));
- intAscii = intAscii + 5;
- strEncryPwd += (char) intAscii;
- }
- return strEncryPwd;
- }
And for decrypting the password, here is my method:
- public string DecryptPwd(string strEncryptedPwd)
- {
-
-
-
-
- int intAscii;
- string strDecryPwd = "";
- for (int intIndex = 0; intIndex < strEncryptedPwd.ToString().Length; intIndex++)
- {
- intAscii = (int) char.Parse(strEncryptedPwd.ToString().Substring(intIndex, 1));
- intAscii = intAscii - 5;
- strDecryPwd += (char) intAscii;
- }
-
- return strDecryPwd;
- }
The main thing here i did for encryption is:
- Finding the ASCII key of the letter entered as password.
- Adding +5 to each ascii key.
- similarly while DECRYPT my password finding the ASCII key and subtracting -5 from that to get the original data.
Now call the encrypt method on Encrypt button click.
- protected void btn_subbmit_Click(object sender, EventArgs e)
- {
- string password = txt_password.Text;
- string encript = EncryptPwd(password);
- Response.Write("The Encripted password is:"+encript);
- }
Now this will be like-
Now for decrypting the same password in original form, place the password in decrypt textbox and press the decrypt button.
Here is how this decrypt button will work.
- protected void btn_decrypt_Click(object sender, EventArgs e)
- {
- string depasstxt = txt_enpass.Text;
- string encript = DecryptPwd(depasstxt);
- Response.Write("The Password is:" + encript);
- }
And my form will be like the following:
Thus in this way we can manage encryption and decryption of password in our project.