Hash Passwords

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

Hash Passwords

This C# program uses the BCrypt (BCrypt.Net) password hashing function to hash all the clear text passwords in a database.


This program uses BCrypt.Net v0.1 in an APS.NET 4.0 Winforms application to perform a one-way hash on all the clear-text passwords in a database.

.Hash Password Program


Hash Passwords Screen

The user tables are read into an ADO.NET dataset, then the rows in the dataset are looped through with each password field being hashed
by the BCrypt algorithm. The dataset is then looped through again to update the database table with the hashed password.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Text;
using System.Data;
using System.Diagnostics;

namespace HashPasswords
{
    public partial class Form1 : Form
    {
        private string connConnectionString = "Conn";

        public Form1()
        {
            InitializeComponent();
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings[connConnectionString].ConnectionString;

            string strSQLWriter = "SELECT COUNT(*) FROM writer";
            MySqlCommand cmdWriter = new MySqlCommand(strSQLWriter, conn);
            conn.Open();
            var rowCountWriter = cmdWriter.ExecuteScalar();
            conn.Close();
            lblWriterTotal.Text = "writer total rows: " + Convert.ToInt32(rowCountWriter);
            lblWriterHashed.Text = "writer hashed rows: 0";

            string strSQLUser = "SELECT COUNT(*) FROM user";
            MySqlCommand cmdUser = new MySqlCommand(strSQLUser, conn);
            conn.Open();
            var rowCountUser = cmdUser.ExecuteScalar();
            conn.Close();
            lblUserTotal.Text = "user total rows: " + Convert.ToInt32(rowCountUser);
            lblUserHashed.Text = "user hashed rows: 0";

        }

        private void btnHash_Click(object sender, EventArgs e)
        {
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings[connConnectionString].ConnectionString;

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();            

            // Loop thru rows in writer table updating Password column
            string strSQLWriter = "SELECT * FROM writer";
            MySqlCommand cmdWriter = new MySqlCommand(strSQLWriter, conn);
            var dsWriter = new DataSet();
            var dsAdapter = new MySqlDataAdapter(cmdWriter);
            dsAdapter.Fill(dsWriter, "writer");

            byte[] thePassword;
            int countWriterPasswords = 0;
            MySqlCommand cmdWriterUpdate = new MySqlCommand();
            cmdWriterUpdate.Connection = new MySqlConnection(conn.ConnectionString);
            cmdWriterUpdate.Connection.Open();
            string strSQLWriterUpdate = "UPDATE writer " +
                "SET Password=?Password " +
                "WHERE WriterID = ?WriterID";
            cmdWriterUpdate.CommandText = strSQLWriterUpdate;

            foreach (DataRow row in dsWriter.Tables["writer"].Rows)
            {
                if ((row["pword"] != DBNull.Value) && (row["Password"] == DBNull.Value))
                {
                    thePassword = (byte[])row["pword"];
                    if (thePassword.Length > 0)
                    {
                        string stringPassword = Encoding.Default.GetString(thePassword);
                        string hashedPassword = BCrypt.Net.BCrypt.HashPassword(stringPassword, BCrypt.Net.BCrypt.GenerateSalt(12));
                        byte[] binaryPassword = Encoding.Default.GetBytes(hashedPassword);
                        cmdWriterUpdate.Parameters.Clear();
                        cmdWriterUpdate.Parameters.AddWithValue("Password", binaryPassword);
                        cmdWriterUpdate.Parameters.AddWithValue("WriterID", row["WriterID"].ToString());
                        cmdWriterUpdate.ExecuteNonQuery();
                        countWriterPasswords++;
                    }
                }
            }
            cmdWriterUpdate.Connection.Close();

            lblWriterHashed.Text = "writer hashed rows: " + countWriterPasswords;

            // Loop thru rows in user table updating Password column
            string strSQLUser = "SELECT * FROM user";
            MySqlCommand cmdUser = new MySqlCommand(strSQLUser, conn);
            var dsUser = new DataSet();
            var dsAdapterUser = new MySqlDataAdapter(cmdUser);
            dsAdapterUser.Fill(dsUser, "user");

            string theUserPassword;
            int countUserPasswords = 0;
            MySqlCommand cmdUserUpdate = new MySqlCommand();
            cmdUserUpdate.Connection = new MySqlConnection(conn.ConnectionString);
            cmdUserUpdate.Connection.Open();
            string strSQLUserUpdate = "UPDATE user " +
                "SET Password=?Password " +
                "WHERE Num = ?UserID";
            cmdUserUpdate.CommandText = strSQLUserUpdate;
            foreach (DataRow row in dsUser.Tables["user"].Rows)
            {
                if ((row["Pswd"] != DBNull.Value) && (row["Password"] == DBNull.Value))
                {
                    theUserPassword = row["Pswd"].ToString();
                    if (theUserPassword != "")
                    {
                        string hashedPassword = BCrypt.Net.BCrypt.HashPassword(theUserPassword, BCrypt.Net.BCrypt.GenerateSalt(12));
                        byte[] binaryPassword = Encoding.Default.GetBytes(hashedPassword);
                        cmdUserUpdate.Parameters.Clear();
                        cmdUserUpdate.Parameters.AddWithValue("Password", binaryPassword);
                        cmdUserUpdate.Parameters.AddWithValue("UserID", row["Num"].ToString());
                        cmdUserUpdate.ExecuteNonQuery();
                        countUserPasswords++;
                    }
                }
            }
            cmdUserUpdate.Connection.Close();

            stopwatch.Stop();
            lblRunTime.Text = "Elapsed Time:" + stopwatch.Elapsed.ToString();

            lblUserHashed.Text = "user hashed rows: " + countUserPasswords;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }
    }
}


Form1.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace IwHashPasswords
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}


Program.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <!--Production Connection String-->
    <add name="Conn" connectionString="server=xxxxxxx;user id=xxxxxxx;password=xxxxxxxx;database=xxxxxxxx;Connection Timeout=60" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.8.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</configuration>


app.config

References



Error | ASP.NET Developer

Error

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/common.inc:2748) in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/kcshadow.net/aspnet/includes/bootstrap.inc).
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'185.176.40.58' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://www.kcshadow.net/aspnet/?q=hashpasswords [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 54.162.171.242 [:db_insert_placeholder_9] => 1534728108 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/kcshadow.net/aspnet/modules/dblog/dblog.module).
The website encountered an unexpected error. Please try again later.