How to generate a random Md5 hash value in C#?
            Asked
            
        
        
            Active
            
        
            Viewed 2.7k times
        
    10
            
            
        - 
                    3Create random string - and generate md5 for it. But why do you want something like that. If you want unique id then just use `Guid` – Stecya May 03 '11 at 11:00
 - 
                    how to create a random string ? – Sudantha May 03 '11 at 11:00
 - 
                    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). – crypted May 03 '11 at 11:03
 - 
                    @Sudantha - see this answer http://stackoverflow.com/questions/1122483/c-random-string-generator/1122519#1122519 – Stecya May 03 '11 at 11:04
 - 
                    5@Int3: No, that is not correct. MD5 hashes only contain digits and the characters a, b, c, d, e and f (hexadecimal). – Marius Schulz May 03 '11 at 11:04
 
3 Answers
25
            
            
        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();
        LukeH
        
- 263,068
 - 57
 - 365
 - 409
 
23
            You could create a random string using Guid.NewGuid() and generate its MD5 checksum.
        Marius Schulz
        
- 15,976
 - 12
 - 63
 - 97
 
- 
                    3Though 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. – Artemix Sep 23 '11 at 16:52
 - 
                    
 
4
            
            
        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();
}
        Martijn Pieters
        
- 1,048,767
 - 296
 - 4,058
 - 3,343
 
        Satinder singh
        
- 10,100
 - 16
 - 60
 - 102