2011-05-03 100 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?