#2 Members - Reputation: 1050
Posted 05 August 2012 - 12:16 PM
Encryptincreptate
Encryptionincreptation
You haven't asked a question either
I assume your looking for help on how to store a string safely using an MD5 checksum in C#.
I've never worked with MD5's but this might be of help: http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5cryptoserviceprovider(v=vs.80).aspx
Just incase you wanted to know how I found that:
http://lmgtfy.com/?q=how+to+use+MD5+C%23
Edited by 6677, 05 August 2012 - 12:21 PM.
#3 Members - Reputation: 132
Posted 05 August 2012 - 12:43 PM
this a password md5 with salt
i only find the md5 with salt in php and javascript
this is my code
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[i].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();
}
}
}
#6 Members - Reputation: 720
Posted 05 August 2012 - 04:03 PM
#7 Members - Reputation: 202
Posted 05 August 2012 - 05:32 PM
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.
#9 Crossbones+ - Reputation: 3559
Posted 05 August 2012 - 07:05 PM
Or, you know, use bcrypt/scrypt. It's intentionally slow and memory-greedy, to defeat hardware attacks and has been designed specifically, by cryptographers, with password hashing in mind. But apparently this is not a possibility at this moment for the OP. Still what is the problem you're having Landi20? You still haven't asked a single question, you just gave us code and told us what it presumably does... what sort of answer do you expect?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.
Edited by Bacterius, 05 August 2012 - 07:07 PM.
#10 Members - Reputation: 132
Posted 05 August 2012 - 07:27 PM
this my code
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[i].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[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// 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[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// 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[i] = 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();
}
}
}
Edited by Landi20, 06 August 2012 - 10:00 AM.
#11 Members - Reputation: 202
Posted 06 August 2012 - 07:05 PM
#13 Crossbones+ - Reputation: 3559
Posted 07 August 2012 - 06:41 PM
Well you are converting the "hash||salt" string into a base64-encoded string at the end of the method, so it will show up garbled. If you want to output it formatted (which you probably do, since you need to know the length of the hash to be able to separate them again later on, unless you somehow keep track of the algorithm used), you should go: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);
... or whatever the hexadecimal conversion function is in C#. Then you will get an output of the form [hash in hexadecimal]:[salt in base64]. Or something like that.
Edited by Bacterius, 07 August 2012 - 06:42 PM.
#14 Members - Reputation: 132
Posted 08 August 2012 - 07:07 AM
i have to put the code in password.cs our logon.cs
i put in logon.cs and have this errors
i change for this
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[i].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[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// 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[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// 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[i] = 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();
}
}
}
and i have some errorError 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
Edited by Landi20, 08 August 2012 - 08:56 AM.
#15 Members - Reputation: 1673
Posted 08 August 2012 - 09:47 AM
You're getting those errors because those methods don't exist, which is why Bacterius saidError 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#.
For the hex string, you can use BitConverter.ToString like in the last example shown here.
#16 Members - Reputation: 132
Posted 08 August 2012 - 10:34 AM
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[i].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[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// 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[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// 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[i] = 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();
}
}
}
i can resolve the problembut i don´t have error but i have the same result
what i have to invoke the function
i make some modification in this function ComputeHash()
Edited by Landi20, 08 August 2012 - 10:50 AM.
#17 Moderators - Reputation: 5061
Posted 08 August 2012 - 11:48 AM
One way to get such clarity is to reduce the amount of code in the example. For example, create a new console project and trying to get the hashing/verification working with a hard-coded hash and salt. This removed all the GUI and database stuff for the time being, until you have the hashing part well understood. An incomplete example would be like the following:
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...");
}
}
}
The SimpleHash class has been put in a separate file. Now, this example does not work (I don't have time to complete it). But it illustrates an important idea, a minimal example that, combined with your "SimpleHash" code in a separate file, allows all of us to actually run your code and see the behaviour and any error messages. From quickly experimenting with the code, it appears that there are asymmetries between the output format of ComputeAndHash and the expected format of VerifyHash, or I have not understood the correct usage of the API.Some other things I noticed;
You appear to be double hashing the input. I don't see why the result of Password.ComputeSaltedHash() should be passed through yet another hashing algorithm.
It doesn't make any sense to randomly generate a salt during verification. The salt must be generated during sign-up, and stored in the database. When the user logs in, select the salt and hash using their user name. Compute the verification hash using the provided password and the salt from the database. Compare with the actual hash that was selected.
This is what the following line seems to be saying:
// NOTE: you store the salt and the salted hash in the datbase
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.
#18 Members - Reputation: 132
Posted 08 August 2012 - 12:03 PM
i want make like this password 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT and i have this result The MD5 hash of 123 is: Ys3ARluCr6wKdd+tHsyBLw==
and i expecte password like this 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT and don´t have error
i can´t find the problem becouse i dont have some error
the code of the class password
i use this website to make my md5 with salt
link http://www.obviex.com/samples/hash.aspx
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[i] = _allowedChars[(int)randomBytes[i] % 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[i].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[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// 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[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// 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[i] = 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();
}
}
}
Edited by Landi20, 08 August 2012 - 12:48 PM.
#19 Moderators - Reputation: 5061
Posted 08 August 2012 - 05:16 PM
First a warning, if this program is for public distribution then you absolutely should not authenticate directly against the database. Your database must not be accessible to random Internet users. If you want to distribute this program to other people, you will need to create a server infrastructure to perform the authentication. This could be a simple PHP script, or some kind of Joomla "plugin" (I'm not familiar with Joomla). The client would talk to the server, and the server can then delegate to the Joomla database if that is what you want.
Assuming this is a private client for your own use, then something like the following should work:
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...");
}
}
}
}
I used an online Joomla password tool to encode "topsecret" as the value in this program's source.You'll have to wire this into your current code, including extraction and parsing of the column, etc.
#20 Members - Reputation: 132
Posted 09 August 2012 - 10:45 AM
the code like this
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[i].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[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
// 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[i] = hashBytes[i];
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
// 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[i] = 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();
}
}
}
but i have a problem it is the result it is The MD5 hash of 1 is: 8284615a1dc08e26b6c5921320c036b1. and not 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YTthis password its a exemple






