C#.net Wndows Form application to Encrypt passwords in a table

Password Encryption using c#.net



A windows Form application to encrypt the passwords.



Encryption refers to algorithmic schemes that encode plain text into non-readable form or cyphertext, providing privacy.

Suppose there is a database and that database contains a table that maintains user details like user-Id, username and password.
Suppose we need to encrypt the passwords for the corresponding users.

The code below helps to encrypt all the passwords in the table.

Before going to the code let us briefly see the Added advantage of this code.




? Hard-coding of data is avoided.
? The connection String, database name and table name are all read from an xml file. This helps to use the application for different databases by just changing the values in xml file.
? An Sql Transaction is added to the encryption. This is because say the database has some 10000 records and after encrypting 6500 records an exception occurs. In such scenario, some of the data will be encrypted and some data will be unencrypted. To avoid this we enclose our updation within an sql transaction wherein either all the data will be encrypted and updated or no record will be updated.
? Using MD5 Encryption Technique.
? The userid and passwords fetched from the database before encryption is stored in a hash table.
? Any errors or exceptions caught will be logged into a text file.
? Appropriate messages are displayed on the window depending on success or failure.


Note: The Form or window includes a button and 3 labels to display appropriate messages since it is a windows form application.

Now lets see the Code.

The XML file from where the connection string, database name and table name are read.



server=(The server name or its Ip address);
database=(database_name);user id =(username);
pwd =(password)!;

userdata
D9FF249F-4ADA-4767-A46F-642D7E57BBA1



The code to fetch the passwords from the database, encrypt it and then update it to the database.
When the button is clicked, a confirmation box will be shown and the above operation is done.



namespace PasswordEncryption
{
public partial class Form1 : Form
{
string ConnectionString = null;
string flag = null;
string tableName = null;
static string cryptoGuid = null;
private readonly static byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };
public static string encryptFlag = "false";
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
DialogResult alertres = MessageBox.Show("Are you sure you want to Encrypt the passwords?","Encryption Tool", MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2);
if (alertres.ToString() == "Yes")
{
try
{
// To Read data from XML
XmlTextReader reader;
XmlDocument doc = new XmlDocument();
reader = new XmlTextReader(@"web.xml");
doc.Load(reader);
reader.Close();
XmlNodeList newXMLNodes = doc.SelectNodes("//element1");
foreach (XmlNode newXMLNode in newXMLNodes)
{
ConnectionString = newXMLNode["connectionString"].InnerText;
tableName = newXMLNode["tablename"].InnerText;
cryptoGuid = newXMLNode["CryptoGuid"].InnerText;
// Calling the function to fetch records and update them
FetchAndEncryptPassword(tableName, ConnectionString);
}
}
catch (Exception ex)
{
label2.Text = "";
label3.Text = " One of the input is invalid";
LogMessage(ex.StackTrace + label2.Text);
}
}
}

// To fetch the data from database, store it in a hash table, encrypt it and then update to the database
public void FetchAndEncryptPassword(String table_name, String ConnectionString)
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
string keyValueHash = string.Empty;
string passWordHash;
string encryptedPassword;
try
{
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand1 = new SqlCommand("select userid,password from " + table_name , myConnection);
myReader = myCommand1.ExecuteReader();
String keyValue = null;
String passWord = null;
Hashtable hshTable = new Hashtable();
while (myReader.Read())
{
keyValue = myReader["userId"].ToString();
passWord = myReader["password"].ToString();
hshTable.Add(keyValue, passWord);
}
IDictionaryEnumerator enumObj = hshTable.GetEnumerator();
myReader.Close();
SqlTransaction sqlTrans = myConnection.BeginTransaction();
SqlCommand myCommand2 = new SqlCommand();
myCommand2.CommandType = System.Data.CommandType.Text;
myCommand2.Transaction = sqlTrans;
try
{
while (enumObj.MoveNext())
{
keyValueHash = enumObj.Key.ToString();
passWordHash = enumObj.Value.ToString();
// Calling the function to encrypt password
encryptedPassword = EncryptPassword(passWordHash);
myCommand2.CommandText = "UPDATE " + table_name + " SET password ='" + encryptedPassword + "'" + "where userid ='" + keyValueHash + "'";
myCommand2.Connection = myConnection;
myCommand2.ExecuteNonQuery();
}
sqlTrans.Commit();
label2.Text = "Password Encrypted Successfully..";
LogMessage(label2.Text);
}
catch(Exception ex)
{
sqlTrans.Rollback();
label2.Text = "";
label3.Text = "Encryption Failed."+"\nPlease check the Log file";
string logMessage = "The error occured for user :" + keyValueHash + " : " + label3.Text + ":" + ex.StackTrace;
LogMessage(logMessage);
}
}
catch (Exception e)
{
label2.Text = "";
label3.Text = "Encryption Failed ";
LogMessage(e.StackTrace);
}
finally
{
myConnection.Close();
}
}

// Function to Encrypt the password using MD5 algorithm

public static string EncryptPassword(string userPassword)
{
if (!string.IsNullOrEmpty(userPassword))
{
try
{
string cryptoKey = cryptoGuid;
byte[] buffer = Encoding.ASCII.GetBytes(userPassword);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
des.IV = IV;
return Convert.ToBase64String(des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
}
catch (Exception ex)
{
LogMessage(ex.StackTrace);
}
}
return string.Empty;
}

// Function to log the messages into a text file

public static void LogMessage(string errorMessage)
{
try
{
string path = "Error" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
// if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
if (!File.Exists(System.IO.Path.GetFullPath(path)))
{
File.Create(System.IO.Path.GetFullPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.IO.Path.GetFullPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("___________________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
LogMessage(ex.StackTrace);
}
}
}
}


Regards,
Ramesh


Comments

Guest Author: mosh03 Jun 2012

hi thanks

how can password be retrieve n decrypt



  • 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:
    Email: