C# Generate a random Md5 Hash

24,308

Solution 1

You could create a random string using Guid.NewGuid() and generate its MD5 checksum.

Solution 2

A random MD5 hash value is effectively just a 128-bit crypto-strength random number.

var bytes = new byte[16];
using (var rng = new RNGCryptoServiceProvider())
{
    rng.GetBytes(bytes);
}

// and if you need it as a string...
string hash1 = BitConverter.ToString(bytes);

// or maybe...
string hash2 = BitConverter.ToString(bytes).Replace("-", "").ToLower();

Solution 3

using System.Text;
using System.Security.Cryptography;

  public static string ConvertStringtoMD5(string strword)
{
    MD5 md5 = MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strword);
    byte[] hash = md5.ComputeHash(inputBytes);
    StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
       { 
            sb.Append(hash[i].ToString("x2"));
       }
       return sb.ToString();
}
Share:
24,308
Sudantha
Author by

Sudantha

Interested in Web application development specially in PHP , Cryptography

Updated on July 10, 2022

Comments

  • Sudantha
    Sudantha almost 2 years

    How to generate a random Md5 hash value in C#?

    • Stecya
      Stecya about 13 years
      Create random string - and generate md5 for it. But why do you want something like that. If you want unique id then just use Guid
    • Sudantha
      Sudantha about 13 years
      how to create a random string ?
    • crypted
      crypted about 13 years
      Why would anyone need to create Random MD5 hash. Any string that is of 128 length can be a random md5 hash(at least i guess).
    • Stecya
      Stecya about 13 years
    • Marius Schulz
      Marius Schulz about 13 years
      @Int3: No, that is not correct. MD5 hashes only contain digits and the characters a, b, c, d, e and f (hexadecimal).
  • Artemix
    Artemix almost 13 years
    Though Guid is 128-bit random value, 6 bits are predefined. So, even after hashing you will have only 2^122 different hash values. Using RNGCryptoServiceProvider you'll have all 2^128 values. Actually Guid internally also uses RNGCryptoServiceProvider.
  • Yini
    Yini over 2 years
    I am afraid Guid.NewGuid() is NOT random.