【问题标题】:How to generate MD5 Hash(32/64 Characters) from an integer如何从整数生成 MD5 哈希(32/64 个字符)
【发布时间】:2016-01-29 07:05:09
【问题描述】:

我已经谷歌搜索并检查过

如何从整数生成 MD5 Hash(32/64 个字符)?

我得到的是从字符串或字节数组生成 MD5 哈希字符串的示例。但就我而言,我需要获取整数的 MD5 哈希。

我知道GetHashCode() 方法用于获取整数的哈希码。但是这种方法不适用于我的情况。

是否需要将整数转换为字符串或字节数组才能获得预期的 MD5 哈希字符串?

【问题讨论】:

  • 这在很大程度上取决于您期望的输出类型。您可以散列字符串表示形式,也可以散列整数的字节;两者都是有效的,但会产生不同的结果。
  • 除非您的整数是“特殊”长整数(如 BigInteger),否则它是 32 位或 64 位值。 MD5 散列是一个 128 位的值,那么为什么要散列一个整数呢?您可以只使用整数作为哈希值,即使现在每个“哈希”都是唯一的。例如,两个不同的整数不会有相同的“哈希”值。

标签: c# .net hash integer md5


【解决方案1】:

类似这样的:

  int source = 123;
  String hash;

  // Do not omit "using" - should be disposed
  using (var md5 = System.Security.Cryptography.MD5.Create()) 
  {
    hash = String.Concat(md5.ComputeHash(BitConverter
      .GetBytes(source))
      .Select(x => x.ToString("x2")));
  }

  // Test
  // d119fabe038bc5d0496051658fd205e6
  Console.Write(hash);

【讨论】:

    【解决方案2】:

    如果你想知道“生命的意义”的md5 hash是什么可以

    int meaningOfLife = 42;
    var result = CalculateMD5Hash(""+meaningOfLife);
    

    这假设你可以

    public string CalculateMD5Hash(string input)
    {
        // step 1, calculate MD5 hash from input
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);
    
        // step 2, convert byte array to hex string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }
    

    【讨论】:

    • 除此之外,我不明白你为什么要这样做,整数存储在 4 个字节中,你想要 16 个字节的 md5 表示。您确实想要占用 x4 倍空间的数字表示,它不添加任何内容,因为这很容易可逆。
    • 这也是懒惰的,假设 .NET 会通过将整数附加到字符串来为您完成从整数到字符串的转换。
    【解决方案3】:

    首先您需要将整数转换为字节数组,然后您可以这样做:

    byte[] hashValue;
    using (var md5 = MD5.Create())
    {
        hashValue = md5.ComputeHash(BitConverter.GetBytes(5));
    }
    

    【讨论】:

    • 由于System.Security.Cryptography.MD5 实现IDisposable 你必须dispose创建的实例
    【解决方案4】:

    你可以试试这个,

    int intValue = ; // your value
    byte[] intBytes = BitConverter.GetBytes(intValue);
    Array.Reverse(intBytes);
    byte[] result = intBytes; // you are most probably working on a little-endian machine
    byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(result);
    
    // string representation (similar to UNIX format)
    string encoded = BitConverter.ToString(hash)
       // without dashes
       .Replace("-", string.Empty)
       // make lowercase
       .ToLower();
    

    【讨论】:

      【解决方案5】:

      谢谢大家。在参考了所有答案之后,我在这里发布我的答案,其中包含用于从整数/字符串/字节数组生成“MD5 哈希(32/64 个字符)”的通用方法。可能对其他人有帮助。

      using System;
      using System.Security.Cryptography;
      using System.Text;
      using System.Linq;
      
      namespace ConvertIntToHashCodeConsoleApp
      {
          class Program
          {
              static void Main(string[] args)
              {
                  int number = 100;
                  Console.WriteLine(GetHashMD5(number.ToString()));
                  Console.WriteLine(GetHashStringFromInteger(number));
                  Console.Read();
              }
              /// <summary>
              /// Get the Hash Value for MD5 Hash(32 Characters) from an integer
              /// </summary>
              /// <param name="number"></param>
              /// <returns></returns>
              public static string GetHashStringFromInteger(int number)
              {
                  string hash;
                  using (var md5 = System.Security.Cryptography.MD5.Create())
                  {
                      hash = String.Concat(md5.ComputeHash(BitConverter
                        .GetBytes(number))
                        .Select(x => x.ToString("x2")));
                  }
                  return hash;
              }
      
              /// <summary>
              /// Get the Hash Value for sha256 Hash(64 Characters)
              /// </summary>
              /// <param name="data">The Input Data</param>
              /// <returns></returns>
              public static string GetHash256(string data)
              {
                  string hashResult = string.Empty;
      
                  if (data != null)
                  {
                      using (SHA256 sha256 = SHA256Managed.Create())
                      {
                          byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
                          byte[] dataBufferHashed = sha256.ComputeHash(dataBuffer);
                          hashResult = GetHashString(dataBufferHashed);
                      }
                  }
                  return hashResult;
              }
      
              /// <summary>
              /// Get the Hash Value for MD5 Hash(32 Characters)
              /// </summary>
              /// <param name="data">The Input Data</param>
              /// <returns></returns>
              public static string GetHashMD5(string data)
              {
                  string hashResult = string.Empty;
                  if (data != null)
                  {
                      using (MD5 md5 = MD5.Create())
                      {
                          byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
                          byte[] dataBufferHashed = md5.ComputeHash(dataBuffer);
                          hashResult = GetHashString(dataBufferHashed);
                      }
                  }
                  return hashResult;
              }
              /// <summary>
              /// Get the Encrypted Hash Data
              /// </summary>
              /// <param name="dataBufferHashed">Buffered Hash Data</param>
              /// <returns> Encrypted hash String </returns>
              private static string GetHashString(byte[] dataBufferHashed)
              {
                  StringBuilder sb = new StringBuilder();
                  foreach (byte b in dataBufferHashed)
                  {
                      sb.Append(b.ToString("X2"));
                  }
                  return sb.ToString();
              }
          }
      }
      

      随时欢迎修改/对此代码提供任何更好的解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-24
        • 1970-01-01
        • 2011-06-28
        • 2011-04-01
        • 2018-12-10
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        相关资源
        最近更新 更多