2011-05-03 119 views
4

如何在C#中生成隨機Md5哈希值?C#生成隨機Md5哈希

+3

創建隨機字符串 - 併爲它生成MD5。但你爲什麼要這樣的東西。如果你想要唯一的ID,那麼只需使用'Guid' – Stecya 2011-05-03 11:00:18

+0

如何創建一個隨機字符串? – Sudantha 2011-05-03 11:00:58

+0

爲什麼任何人需要創建隨機MD5散列。 長度爲128的任何字符串都可以是隨機的md5散列(至少我猜)。 – crypted 2011-05-03 11:03:18

回答

12

只需使用Guid.NewGuid()創建一個隨機字符串並生成其MD5校驗和。

+0

雖然Guid是128位隨機值,但預定義了6位。所以,即使在哈希之後,您將只有2^122個不同的哈希值。使用RNGCryptoServiceProvider,你將擁有所有2^128的值。其實Guid內部也使用RNGCryptoServiceProvider。 – Artemix 2011-09-23 16:52:49

17

隨機的MD5哈希值實際上只是一個128位的密碼強度隨機數。

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(); 
+0

謝謝我使用了'Guid' – Sudantha 2011-05-03 11:16:06

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(); 
} 

博客文章:How to convert string into MD5 hash?