Original Post
i want increptate my password with md5+salt in c#
i want the same increptation with my site it is made with joomla 2.5
i want the same increptation with my site it is made with joomla 2.5
increptate
increptation
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
private void LoginBtnClick(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{
using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + hash+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
Form1 ola1 = new Form1();
ola1.Show();
Hide();
// new Client(usernameTxt.Text.Trim(), this).Show();
// Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
}
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
You'd be better off using SHA than MD5. MD5 gets a little more dangerous every year.
Also, if you can run an MD5, adding a salt before the hash really shouldn't be anything more than concatenating or modifying the password in some simple way. Come up with your own simple hash algorithm. That in itself could be your pre-hash salt. Or just MD5 it twice. Or MD5 then SHA.
Finally, just want to say that you are not encrypting. Encryption is reversible. Hashing is not.
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
/// <summary>
/// Generates a hash for the given plain text value and returns a
/// base64-encoded result. Before the hash is computed, a random salt
/// is generated and appended to the plain text. This salt is stored at
/// the end of the hash value, so it can be used later for hash
/// verification.
/// </summary>
/// <param name="plainText">
/// Plaintext value to be hashed. The function does not check whether
/// this parameter is null.
/// </param>
/// <param name="hashAlgorithm">
/// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
/// "SHA256", "SHA384", and "SHA512" (if any other value is specified
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// </param>
/// <param name="saltBytes">
/// Salt bytes. This parameter can be null, in which case a random salt
/// value will be generated.
/// </param>
/// <returns>
/// Hash value formatted as a base64-encoded string.
/// </returns>
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(hashWithSaltBytes);
// Return the result.
return hashValue;
}
/// <summary>
/// Compares a hash of the specified plain text value to a given hash
/// value. Plain text is hashed with the same salt value as the original
/// hash.
/// </summary>
/// <param name="plainText">
/// Plain text to be verified against the specified hash. The function
/// does not check whether this parameter is null.
/// </param>
/// <param name="hashAlgorithm">
/// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
/// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// </param>
/// <param name="hashValue">
/// Base64-encoded hash value produced by ComputeHash function. This value
/// includes the original salt appended to it.
/// </param>
/// <returns>
/// If computed hash mathes the specified hash the function the return
/// value is true; otherwise, the function returns false.
/// </returns>
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}
private void LoginBtnClick(object sender, EventArgs e)
{
string password = usernameTxt.Text.Trim(); // original password
// string wrongPassword = "password"; // wrong password
string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
byte[] data = System.Text.Encoding.ASCII.GetBytes(password+salt);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
/* using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();
// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
// }
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
the code works but i can´t make like this 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT
and the result i have it is kBBoztuz2bU2vou/jtctxcQ==
and i don´t find the problem
return Convert.ToHex(hashBytes) + ":" + Convert.ToBase64(saltBytes);
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
return Convert.ToHex(hashBytes) + ":" + Convert.ToBase64(saltBytes);
// Return the result.
//return hashValue;
}
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}
private void LoginBtnClick(object sender, EventArgs e)
{
string password = usernameTxt.Text.Trim(); // original password
// string wrongPassword = "password"; // wrong password
string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ //String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
// using (MD5 md5Hash = MD5.Create())
/*{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/
// String pass2;
//pass2 = Password.CreateRandomPassword(32);
// Debug output
// Console.WriteLine(pass2);
// Generate a new random salt
int mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(password,mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the datbase
string strHashedPassword = pwd.ComputeSaltedHash();
// Debug output
Console.WriteLine(strHashedPassword);
// byte[] ola = Convert.ToHex(password) + ":" + Convert.ToBase64(strHashedPassword);
byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();
// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
// }
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Error 1 'System.Convert' does not contain a definition for 'ToHex' C:\Users\Alves\Dropbox\Jogos\FirstGame\Client\Logon.cs 154 32 Client
Error 2 'System.Convert' does not contain a definition for 'ToBase64' C:\Users\Alves\Dropbox\Jogos\FirstGame\Client\Logon.cs 154 65 Client
... or whatever the hexadecimal conversion function is in C#.
[/quote]
For the hex string, you can use BitConverter.ToString like in the last example shown here.
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
return BitConverter.ToString(hashBytes) + ":" + Convert.ToBase64String(saltBytes);
// Return the result.
//return hashValue;
}
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}
private void LoginBtnClick(object sender, EventArgs e)
{
string password = usernameTxt.Text.Trim(); // original password
// string wrongPassword = "password"; // wrong password
string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ //String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
// using (MD5 md5Hash = MD5.Create())
/*{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/
// String pass2;
//pass2 = Password.CreateRandomPassword(32);
// Debug output
// Console.WriteLine(pass2);
// Generate a new random salt
int mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(password,mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the datbase
string strHashedPassword = pwd.ComputeSaltedHash();
// Debug output
Console.WriteLine(strHashedPassword);
// think the problem now it is this lines
byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();
// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
// }
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
class Program
{
static void Main(string[] args)
{
const string Algorithm = "SHA256";
string actualPassword = "topsecret";
byte [] salt = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string expectedHash= SimpleHash.ComputeHash(actualPassword, Algorithm, salt);
Console.WriteLine("Please enter your password: ");
string attemptedPassword = Console.ReadLine();
if(SimpleHash.VerifyHash(attemptedPassword, Algorithm, expectedHash))
{
Console.WriteLine("That is the correct password!");
}
else
{
Console.WriteLine("That password is incorrect...");
}
}
}
// NOTE: you store the salt and the salted hash in the datbase
[/quote]
Also, I would recommend just picking a single hashing algorithm and using that. If possible, this should be bcrypt(), but a modern SHA will suffice too, probably. In my example code I made the algorithm used a named constant.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Client
{
class Password
{
private string _password;
private int _salt;
public Password(string strPassword, int nSalt)
{
_password = strPassword;
_salt = nSalt;
}
public static string CreateRandomPassword(int PasswordLength)
{
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
chars = _allowedChars[(int)randomBytes % allowedCharCount];
}
return new string(chars);
}
public static int CreateRandomSalt()
{
Byte[] _saltBytes = new Byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(_saltBytes);
return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
(((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
}
public string ComputeSaltedHash()
{
// Create Byte array of password string
ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] _secretBytes = encoder.GetBytes(_password);
// Create a new salt
Byte[] _saltBytes = new Byte[4];
_saltBytes[0] = (byte)(_salt >> 24);
_saltBytes[1] = (byte)(_salt >> 16);
_saltBytes[2] = (byte)(_salt >> 8);
_saltBytes[3] = (byte)(_salt);
// append the two arrays
Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);
MD5 sha1 = MD5.Create();
Byte[] computedHash = sha1.ComputeHash(toHash);
return encoder.GetString(computedHash);
}
}
}
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
return BitConverter.ToString(hashBytes) + ":" + Convert.ToBase64String(saltBytes);
// Return the result.
//return hashValue;
}
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}
private void LoginBtnClick(object sender, EventArgs e)
{
string password = usernameTxt.Text.Trim(); // original password
// string wrongPassword = "password"; // wrong password
string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ //String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
// using (MD5 md5Hash = MD5.Create())
/*{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/
// String pass2;
//pass2 = Password.CreateRandomPassword(32);
// Debug output
// Console.WriteLine(pass2);
// Generate a new random salt
int mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(password,mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the datbase
string strHashedPassword = pwd.ComputeSaltedHash();
// Debug output
Console.WriteLine(strHashedPassword);
byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();
// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
// }
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Help
{
class Program
{
// http://stackoverflow.com/questions/1422314/converting-byte-array-to-string-and-back-again-in-c-sharp
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
static void Main(string[] args)
{
ASCIIEncoding Encoding = new ASCIIEncoding();
// An encoded version of "topsecret" with the given salt.
string hashAndSalt = "360b58a3d6e04ec55ee0bab1a74cd467:rsw2iD2cZToBxyg4ZYKrqIzeerLibLlP";
string[] split = hashAndSalt.Split(':');
if (split.Length != 2)
{
// Fail
}
string salt = split[1];
string expectedHash = split[0];
Console.WriteLine("Please enter your password: ");
string plaintext = Console.ReadLine();
string saltAndPlaintext = plaintext + salt;
byte[] saltAndPlainbytes = Encoding.GetBytes(saltAndPlaintext);
byte[] actualBytes = new MD5CryptoServiceProvider().ComputeHash(saltAndPlainbytes);
string actualHash = ByteArrayToString(actualBytes);
if (expectedHash == actualHash)
{
Console.WriteLine("That is the correct password!");
}
else
{
Console.WriteLine("That password is incorrect...");
}
}
}
}
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Client
{
public partial class Logon : Form
{
//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/*
static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 8;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
return BitConverter.ToString(hashBytes) + ":" + Convert.ToBase64String(saltBytes);
// Return the result.
//return hashValue;
}
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
private void LoginBtnClick(object sender, EventArgs e)
{
// string password = usernameTxt.Text.Trim(); // original password
//string wrongPassword = "password"; // wrong password
/*
string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);
*/
MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ ASCIIEncoding Encoding = new ASCIIEncoding();
// An encoded version of "topsecret" with the given salt.
string hashAndSalt = "360b58a3d6e04ec55ee0bab1a74cd467:rsw2iD2cZToBxyg4ZYKrqIzeerLibLlP";
string[] split = hashAndSalt.Split(':');
if (split.Length != 2)
{
// Fail
}
string salt = split[1];
string expectedHash = split[0];
Console.WriteLine("Please enter your password: ");
string plaintext = textBox1.Text.Trim();
string saltAndPlaintext = plaintext + salt;
byte[] saltAndPlainbytes = Encoding.GetBytes(saltAndPlaintext);
byte[] actualBytes = new MD5CryptoServiceProvider().ComputeHash(saltAndPlainbytes);
string actualHash = ByteArrayToString(actualBytes);
if (expectedHash == actualHash)
{
Console.WriteLine("That is the correct password!");
}
else
{
Console.WriteLine("That password is incorrect...");
}
//String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
/* using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
// Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// String pass2;
//pass2 = Password.CreateRandomPassword(32);
// Debug output
// Console.WriteLine(pass2);
*/
// Generate a new random salt
// int mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
// Password pwd = new Password(password,mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the datbase
// string strHashedPassword = pwd.ComputeSaltedHash();
// Debug output
// Console.WriteLine(strHashedPassword);
// byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);
//
// data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
// String ola = Convert.ToBase64String(data);
/*
byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
string ola = Convert.ToBase64String(data);
*/
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + actualHash + ".");
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + actualHash + "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();
// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}
}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
// }
}
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}
private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
This topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more