Jump to content
  • Advertisement
Sign in to follow this  
Pedro Alves

md5+salt

This topic is 2165 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

Advertisement

increptate

Encrypt

increptation

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

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
namespace Client
{

public partial class Logon : Form
{

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


private void LoginBtnClick(object sender, EventArgs e)
{

MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{
using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + hash+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
Form1 ola1 = new Form1();
ola1.Show();

Hide();
// new Client(usernameTxt.Text.Trim(), this).Show();
// Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}


}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
}
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}

private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

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
i want save a string in md5 + salt
becouse i want use my joomla 2.5 to make a login in my applicantion Edited by Landi20

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

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.

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

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Shared.User;
using Client;
using System.Security.Cryptography;
using System.Text;
namespace Client
{

public partial class Logon : Form
{

//Logon Instance { get; set; }
public Logon()
{
InitializeComponent();
}
/* static string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data.ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
// Verify a hash against a string.
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(md5Hash, input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
*/
public class SimpleHash
{
/// <summary>
/// Generates a hash for the given plain text value and returns a
/// base64-encoded result. Before the hash is computed, a random salt
/// is generated and appended to the plain text. This salt is stored at
/// the end of the hash value, so it can be used later for hash
/// verification.
/// </summary>
/// <param name="plainText">
/// Plaintext value to be hashed. The function does not check whether
/// this parameter is null.
/// </param>
/// <param name="hashAlgorithm">
/// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
/// "SHA256", "SHA384", and "SHA512" (if any other value is specified
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// </param>
/// <param name="saltBytes">
/// Salt bytes. This parameter can be null, in which case a random salt
/// value will be generated.
/// </param>
/// <returns>
/// Hash value formatted as a base64-encoded string.
/// </returns>
public static string ComputeHash(string plainText,
string hashAlgorithm,
byte[] saltBytes)
{
// If salt is not specified, generate it on the fly.
if (saltBytes == null)
{
// Define min and max salt sizes.
int minSaltSize = 32;
int maxSaltSize = 32;
// Generate a random number for the size of the salt.
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
// Allocate a byte array, which will hold the salt.
saltBytes = new byte[saltSize];
// Initialize a random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the salt with cryptographically strong byte values.
rng.GetNonZeroBytes(saltBytes);
}
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + saltBytes.Length];
// Copy plain text bytes into resulting array.
for (int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes = plainTextBytes;
// Append salt bytes to the resulting array.
for (int i = 0; i < saltBytes.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes;
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash;
// Make sure hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Initialize appropriate hashing algorithm class.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hash = new SHA1Managed();
break;
case "SHA256":
hash = new SHA256Managed();
break;
case "SHA384":
hash = new SHA384Managed();
break;
case "SHA512":
hash = new SHA512Managed();
break;
default:
hash = new MD5CryptoServiceProvider();
break;
}
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
saltBytes.Length];
// Copy hash bytes into resulting array.
for (int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes = hashBytes;
// Append salt bytes to the result.
for (int i = 0; i < saltBytes.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = saltBytes;
// Convert result into a base64-encoded string.
string hashValue = Convert.ToBase64String(hashWithSaltBytes);
// Return the result.
return hashValue;
}
/// <summary>
/// Compares a hash of the specified plain text value to a given hash
/// value. Plain text is hashed with the same salt value as the original
/// hash.
/// </summary>
/// <param name="plainText">
/// Plain text to be verified against the specified hash. The function
/// does not check whether this parameter is null.
/// </param>
/// <param name="hashAlgorithm">
/// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
/// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
/// MD5 hashing algorithm will be used). This value is case-insensitive.
/// </param>
/// <param name="hashValue">
/// Base64-encoded hash value produced by ComputeHash function. This value
/// includes the original salt appended to it.
/// </param>
/// <returns>
/// If computed hash mathes the specified hash the function the return
/// value is true; otherwise, the function returns false.
/// </returns>
public static bool VerifyHash(string plainText,
string hashAlgorithm,
string hashValue)
{
// Convert base64-encoded hash value into a byte array.
byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
// We must know size of hash (without salt).
int hashSizeInBits, hashSizeInBytes;
// Make sure that hashing algorithm name is specified.
if (hashAlgorithm == null)
hashAlgorithm = "";
// Size of hash is based on the specified algorithm.
switch (hashAlgorithm.ToUpper())
{
case "SHA1":
hashSizeInBits = 160;
break;
case "SHA256":
hashSizeInBits = 256;
break;
case "SHA384":
hashSizeInBits = 384;
break;
case "SHA512":
hashSizeInBits = 512;
break;
default: // Must be MD5
hashSizeInBits = 128;
break;
}
// Convert size of hash from bits to bytes.
hashSizeInBytes = hashSizeInBits / 8;
// Make sure that the specified hash value is long enough.
if (hashWithSaltBytes.Length < hashSizeInBytes)
return false;
// Allocate array to hold original salt bytes retrieved from hash.
byte[] saltBytes = new byte[hashWithSaltBytes.Length -
hashSizeInBytes];
// Copy salt from the end of the hash to the new array.
for (int i = 0; i < saltBytes.Length; i++)
saltBytes = hashWithSaltBytes[hashSizeInBytes + i];
// Compute a new hash string.
string expectedHashString =
ComputeHash(plainText, hashAlgorithm, saltBytes);
// If the computed hash matches the specified hash,
// the plain text value must be correct.
return (hashValue == expectedHashString);
}
}

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

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

MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=Accounts");
try
{ String salt= textBox1.Text.Trim();
//String value = textBox1.Text.Trim();
byte[] data = System.Text.Encoding.ASCII.GetBytes(password+salt);
data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
String ola = Convert.ToBase64String(data);
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + ola + ".");
/* using (MD5 md5Hash = MD5.Create())
{
string hash = GetMd5Hash(md5Hash, textBox1.Text.Trim());
Console.WriteLine("The MD5 hash of " + textBox1.Text.Trim() + " is: " + hash + ".");
//Console.WriteLine("Verifying the hash...");
// if (VerifyMd5Hash(md5Hash, textBox1.Text.Trim(), hash))
// {
// Console.WriteLine("The hashes are the same.");
// }
// else
// {
// Console.WriteLine("The hashes are not same.");
// }
*/
MySqlCommand cmd = new MySqlCommand("SELECT tipo FROM user WHERE username = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + ola+ "' ");
cmd.Connection = con;
con.Open();
object Tipo = cmd.ExecuteScalar();
if (Tipo != null && Tipo != DBNull.Value)
{
switch (System.Convert.ToInt32(Tipo))
{
case 1:
// Form1 ola1 = new Form1();
// ola1.Show();

// Hide();
new Client(usernameTxt.Text.Trim(), this).Show();
Hide();
break;
case 2:
MessageBox.Show("GAME MASTER");
break;
case 3:
MessageBox.Show("Moderador");
break;
case 4:
MessageBox.Show("VIP");
break;
case 5:
MessageBox.Show("Membro");
break;
case 6:
MessageBox.Show("Registo nao foi Activado");
break;
case 7:
MessageBox.Show("O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)");
break;
}

}
else
{
MessageBox.Show("Usuario ou Senha incorretos");
}
}
// }
catch (MySqlException msqle)
{
MessageBox.Show("Erro de acesso ao MySQL : " +
msqle.Message, "Erro");
}
}

private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
loginBtn.PerformClick(); //Perform Login button click if enter is pressed
}
internal static void Exit()
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Edited by Landi20

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!