md5+salt

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
can put my like this my password <span style="background-color:#fafbfc; color:#282828; font-family:helvetica,arial,verdana,tahoma,sans-serif; font-size:13px; line-height:20px 4e9e4bcc5752d6f939aedb42408fd3aa:0vURRbyY8Ea0tlvnTFn7xcKpjTFyn0YT
<span style="color:#282828; font-family:helvetica,arial,verdana,tahoma,sans-serif; font-size:13px; line-height:20px; background-color:#fafbfc and the result i have it is kBBoztuz2bU2vou/jtctxcQ==

this is the code
where is the problem
<pre class="prettyprint using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
using System.Linq;
namespace Client
{

public partial class Logon : Form
{

//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{

public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
return BitConverter.ToString(hashBytes) + ":" + Convert.ToBase64String(saltBytes);

// Return the result.
//return hashValue;
}
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}

private void LoginBtnClick(object sender, EventArgs e)
{
string password = usernameTxt.Text.Trim(); // original password
// string wrongPassword = "password"; // wrong password

string passwordHashMD5 =
SimpleHash.ComputeHash(password, "MD5", null);
string passwordHashSha1 =
SimpleHash.ComputeHash(password, "SHA1", null);
string passwordHashSha256 =
SimpleHash.ComputeHash(password, "SHA256", null);
string passwordHashSha384 =
SimpleHash.ComputeHash(password, "SHA384", null);
string passwordHashSha512 =
SimpleHash.ComputeHash(password, "SHA512", null);

MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ //String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();

// using (MD5 md5Hash = MD5.Create())
/*{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/

// String pass2;
//pass2 = Password.CreateRandomPassword(32);
// Debug output
// Console.WriteLine(pass2);
// Generate a new random salt
int mySalt = Password.CreateRandomSalt();
// Initialize the Password class with the password and salt
Password pwd = new Password(password,mySalt);
// Compute the salted hash
// NOTE: you store the salt and the salted hash in the datbase
string strHashedPassword = pwd.ComputeSaltedHash();
// Debug output
Console.WriteLine(strHashedPassword);
// think the problem now it is this lines

byte[] data = System.Text.Encoding.ASCII.GetBytes(password + strHashedPassword);

data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);

Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = " + usernameTxt.Text.Replace("", "") + " AND password = " + ola+ " ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();

// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banidon 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]
password.cs
the code is
<pre class="prettyprint using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace Client
{
class Password
{
private string _password;
private int _salt;

public Password(string strPassword, int nSalt)
{
_password = strPassword;
_salt = nSalt;
}

public static string CreateRandomPassword(int PasswordLength)
{
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < PasswordLength; i++)
{
chars = _allowedChars[(int)randomBytes % allowedCharCount];
}

return new string(chars);
}

public static int CreateRandomSalt()
{
Byte[] _saltBytes = new Byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(_saltBytes);

return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
(((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
}

public string ComputeSaltedHash()
{
// Create Byte array of password string
ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] _secretBytes = encoder.GetBytes(_password);

// Create a new salt
Byte[] _saltBytes = new Byte[4];
_saltBytes[0] = (byte)(_salt >> 24);
_saltBytes[1] = (byte)(_salt >> 16);
_saltBytes[2] = (byte)(_salt >> 8);
_saltBytes[3] = (byte)(_salt);

// append the two arrays
Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

MD5 sha1 = MD5.Create();
Byte[] computedHash = sha1.ComputeHash(toHash);

return encoder.GetString(computedHash);
}
}


} [/code]
<br/>


View the full article
 
Back
Top