【问题标题】:C# Generate a random Md5 HashC# 生成随机 Md5 哈希
【发布时间】:2011-08-17 15:04:02
【问题描述】:

如何在 C# 中生成随机的 Md5 哈希值?

【问题讨论】:

  • 创建随机字符串 - 并为其生成 md5。但是你为什么想要那样的东西。如果您想要唯一的 ID,那么只需使用 Guid
  • 如何创建随机字符串?
  • 为什么有人需要创建随机 MD5 哈希。任何长度为 128 的字符串都可以是随机 md5 哈希(至少我猜)。
  • @Int3:不,这是不正确的。 MD5 哈希仅包含数字和字符 a、b、c、d、e 和 f(十六进制)。

标签: c# md5


【解决方案1】:

您可以使用Guid.NewGuid() 创建一个随机字符串并生成其 MD5 校验和。

【讨论】:

  • 虽然 Guid 是 128 位随机值,但预定义了 6 位。因此,即使在散列之后,您也只有 2^122 个不同的散列值。使用 RNGCryptoServiceProvider 您将拥有所有 2^128 个值。实际上 Guid 在内部也使用了 RNGCryptoServiceProvider。
  • 恐怕 Guid.NewGuid() 不是随机的。
【解决方案2】:

随机 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();

【讨论】:

    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 2017-05-24
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2011-07-26
      相关资源
      最近更新 更多