Sign in to follow this  

md5+salt

This topic is 1952 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

[quote name='Landi20' timestamp='1344185413' post='4966394']
increptate
[/quote]
Encrypt
[quote name='Landi20' timestamp='1344185413' post='4966394']
increptation
[/quote]
Encryption

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

Share this post


Link to post
Share on other sites
with normal md5 i can make like this Encrypt 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT
this a password md5 with salt
i only find the md5 with salt in php and javascript
this is my code
[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();
}
}
}
[/CODE]

Share this post


Link to post
Share on other sites
Your still not saying what your wanting us to do.
Is english your first language because grammar is rather poor and making it very difficult to understand your post. If english is not your first language then that is fair enough

Share this post


Link to post
Share on other sites
Dont forget to add pepper... Nah check out the bottom of this post. It shows a function for MD5 + salt in C#. http://stackoverflow.com/questions/1300890/md5-hash-with-salt-for-keeping-password-in-db-in-c-sharp

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
[quote name='sooner123' timestamp='1344209547' post='4966489']
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.
[/quote]
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? Edited by Bacterius

Share this post


Link to post
Share on other sites
the problem i can´t put the my password like this 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT
this my code
[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();
}
}
}
[/CODE] Edited by Landi20

Share this post


Link to post
Share on other sites
I think the issue may be that he doesn't really understanding what hashing or salting is. If someone here could surpass the language barrier (or knows a good website that describes the concepts in really simple english) that might help him out.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
[quote name='Landi20' timestamp='1344384266' post='4967197']
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
[/quote]
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:

[CODE]return Convert.ToHex(hashBytes) + ":" + Convert.ToBase64(saltBytes);[/CODE]

... 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

Share this post


Link to post
Share on other sites
i make the changes but i have some errors
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 [CODE]
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();
}
}
}
[/CODE]
and i have some error
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 Edited by Landi20

Share this post


Link to post
Share on other sites
[quote name='Landi20' timestamp='1344431234' post='4967378']
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
[/quote]
You're getting those errors because those methods don't exist, which is why Bacterius said
[quote]
... 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 [url="http://msdn.microsoft.com/en-us/library/bb311038.aspx"]here[/url].

Share this post


Link to post
Share on other sites
i change the code but i have the same problem
[CODE]
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();
}
}
}
[/CODE]
i can resolve the problem
but 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

Share this post


Link to post
Share on other sites
You need to be clearer about what your problem is. You need to explain what is currently happening, what should be happening, and any errors and output you are currently getting, along with a description of what you want/expect to happen.

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:
[code]
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...");
}
}
}

[/code]
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:
[quote]
// 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.

Share this post


Link to post
Share on other sites
white simple hash i can make but when i want put the md5 with salt i can´t make work
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
[CODE]
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);
}
}

}
[/CODE]
[CODE]
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();
}
}
}
[/CODE] Edited by Landi20

Share this post


Link to post
Share on other sites
Ok, I think I can see the problem better now. You have an existing database, which is configured by Joomla. There are existing users in this database. You want to write your own code to authenticate these users against this database.

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:
[code]
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...");
}
}
}
}
[/code]
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.

Share this post


Link to post
Share on other sites
ok
the code like this
[CODE]
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();
}
}
}
[/CODE]
but i have a problem it is the result it is The MD5 hash of 1 is: 8284615a1dc08e26b6c5921320c036b1. and not 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT
this password its a exemple

Share this post


Link to post
Share on other sites
And this is why you should never sign up for membership on random websites unless you use a throw away password and don't provide any sensitive information. If you have to ask this question, you should NOT be writing a login system for a website. You should definitely use bcrypt as Bactarius suggessted as MD5 and SHA are insufficient for secure hashes.


[url="http://www.troyhunt.com/2012/06/our-password-hashing-has-no-clothes.html"]Our Password Hashing Has No Clothes[/url]
Utilizing the GPU, he was able to crack over 24,000 sha hashed and salted passwords in 45 minutes.

Share this post


Link to post
Share on other sites
If you cannot integrate my code, then I would suggest that your current project is beyond your capabilities at this point in time. I recommend you go back and try simpler projects to hone your core language skills.

Share this post


Link to post
Share on other sites
[quote name='tstrimple' timestamp='1344539380' post='4967874']
And this is why you should never sign up for membership on random websites unless you use a throw away password and don't provide any sensitive information. If you have to ask this question, you should NOT be writing a login system for a website. You should definitely use bcrypt as Bactarius suggessted as MD5 and SHA are insufficient for secure hashes.
[/quote]
I completely agree. I mean, it's not like you need to be some sort of god to write security applications as some people around the net would have you believe (hell, I'm writing a cryptography library at this very moment) but you do need to know what you are doing, and if you don't have the experience to decide how to best implement a protocol (from a theoretical as well as practical point of view) and to avoid common pitfalls, you most definitely should not be implementing login systems. You just can't make this stuff up!

(and if you pull out the "but no one will bother breaking my code" excuse, you're doing it wrong - cryptography is all based on worst case analysis, if you try and get away with best case security, you've already failed at a fundamental level)

Share this post


Link to post
Share on other sites
my project is almost complete and the area i very difficult is in security
if use only md5 i can make work but when i use md5 with salt our other tips of cryptography with other cryptography
i can´t make alone
i programmed in java
i post in this forum because i have very difficult to cryptography my passwords
i have to use the same password with the website because my project is in xna
i have to say this a great forum
thanks for the help Edited by Landi20

Share this post


Link to post
Share on other sites

This topic is 1952 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this