How to encrypt a password in a C # program

Source: Internet
Author: User

in ADO, how do I encrypt the password in the data when I add data to the database? (In other words, the user's secret is not visible in the data table

Code, just some compiled string to prevent the database administrator from using the user's password for illegal operation. )
First, the namespace is introduced in the C#winform program, "Using System.Web.Security;", which is specifically used to program the

The security settings of the line;
Next, define a variable of type string, which is used to receive the input password;
String PassWord = This.textBox1.Text.Trim ();
After the password is taken, the password is then encrypted:
string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile (pwd, "MD5");
Finally, add the encrypted password pwd to the database.
Insert into UserInfo (UNAME,PWD) VALUES (' {0} ', ' {1} '), select @ @identity ", This.txtUID.Text.Trim

(), Passwrod);
Example code:
Using System.Web.Security;

Get the password in the text box
string pwd = This.txtPwd1.Text.Trim ();
Encrypt the password
String passwrod = FormsAuthentication.HashPasswordForStoringInConfigFile (pwd, "MD5");
Create an SQL statement to save the encrypted password to the database
String inscmd =
String. Format ("INSERT into UserInfo (UNAME,PWD) VALUES (' {0} ', ' {1} '); select @ @identity",

This.txtUID.Text.Trim (), Passwrod);
using (SqlCommand cmd = new SqlCommand (Inscmd, form1.connection))
{
int uid = convert.toint32 (cmd). ExecuteScalar ());
int uid = Int. Parse (cmd. ExecuteScalar ());//error
if (UID > 0)
{
String mess = String. Format ("Congratulations, registration successful!") Your number is {0} ", UID);
MessageBox.Show (mess);
}
Else
{
MessageBox.Show ("Sorry, registration has failed!") ");
}
}

This ensures the security of the user's password after encryption, but there is a problem, that is, how to authenticate the password when the user logs in, it will not let

Does the user remember the long string of strings after the encryption? The answer, of course, is no, how to solve it?
This should be resolved:
When the user logs in, get the password entered by the user;
Then, the password to be taken is encrypted again;
Then, according to the user name to remove the user's real password in the database;
Finally, the password that was just encrypted is compared with the database password to complete the user logon operation.
Example code:
string pwd = This.txtPwd1.Text.Trim ();
String pwd1 = FormsAuthentication.HashPasswordForStoringInConfigFile (pwd, "MD5");
String uid = This.txtUID.Text.Trim ();
String selcmd = String. Format ("Select pwd from UserINfo where uname= ' {0} '", UID);
string password = "";
using (SqlCommand cmd = new SqlCommand (Selcmd, form1.connection))
{
password= cmd. ExecuteScalar (). ToString ();

}
if (password = = pwd1)
{
MessageBox.Show ("Login Successful");
}
Else
{
MessageBox.Show ("Bad password!") ");
}
Full instance (can be used for replication):

1. Database code:

Use tempdb
Go
if exists (select * from sysobjects where name = ' UserInfo ')
drop table UserInfo
Go
CREATE TABLE UserInfo
(
uId int Identity (*) is not NULL,
UName nvarchar () NOT NULL,
Uage int NOT NULL,
Password nvarchar (+) NOT NULL
)
Go
ALTER TABLE UserInfo
Add constraint Pk_uid primary key (UID)
ALTER TABLE UserInfo
Add constraint ck_uage Check (uage between 0 and 100)
Go
SELECT * FROM UserInfo

2.c# Code

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Data.SqlClient;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using System.Web.Security; Secure encryption

namespace Password Encryption Example
{
public partial class Form1:form
{
Create a database connection string
Static readonly string strconn = "Data source=.;i Nitial catalog=tempdb;integrated security=true ";
Create a database Connection object
static SqlConnection connection = NULL;
Property
public static SqlConnection Connection
{
Get
{
if (connection = = NULL | | connection. State = ConnectionState.Open)
{
Connection = new SqlConnection (strconn); Connecting to a database
Connection.  Open (); Open Database
}
return form1.connection; Returns a connection
}

}

Public Form1 ()
{
InitializeComponent ();
}

<summary>
Check user input
</summary>
<returns></returns>
private bool Checkinput ()
{
if (string. IsNullOrEmpty (This.txtName.Text))
{
This.errorPro.SetError (this.txtname, "User name cannot be empty! ");
This.txtName.Focus ();
return false;
}
Else
{
This.errorPro.Dispose (); Termination prompt Error
}
if (string. IsNullOrEmpty (This.txtAge.Text))
{
This.errorPro.SetError (This.txtage, "name can't be empty!") ");
This.txtAge.Focus ();
return false;
}
Else
{
This.errorPro.Dispose ();
}
if (string. IsNullOrEmpty (This.txtPass.Text))
{
This.errorPro.SetError (This.txtpass, "Password cannot be empty!") ");
}
Else
{
This.errorPro.Dispose ();
}
return true;
}

<summary>
Add data
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void btnAdd_Click (object sender, EventArgs e)
{
if (this. Checkinput ())
{
Get the password entered by the user
string password = This.txtPass.Text.Trim ();
Encrypt the password
string pwd = formsauthentication.hashpasswordforstoringinconfigfile (password, "MD5");
Create an SQL statement to save the encrypted password to the database
String inscmd = String. Format ("INSERT into UserInfo values (' {0} ', ' {1} ', ' {2} ')",
This.txtName.Text.Trim (), This.txtAge.Text.Trim (), PWD);
using (SqlCommand cmd = new SqlCommand (inscmd,form1.connection))
{
if (cmd. ExecuteNonQuery () > 0)
{
MessageBox.Show ("Congratulations, registration is successful!") ");
}
Else
{
MessageBox.Show ("Sorry, registration failed ...");
}
}
}
}
}
}

Finish!

How to encrypt a password in a C # program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.