Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generate a random Md5 Hash

Tags:

c#

md5

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

like image 867
Sudantha Avatar asked May 03 '11 10:05

Sudantha


3 Answers

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();
like image 178
LukeH Avatar answered Oct 18 '22 09:10

LukeH


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

like image 30
Marius Schulz Avatar answered Oct 18 '22 09:10

Marius Schulz


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();
}
like image 22
Satinder singh Avatar answered Oct 18 '22 09:10

Satinder singh