.net 如何从整数生成MD5哈希(32/64个字符)

ecfsfe2w  于 2023-01-14  发布在  .NET
关注(0)|答案(5)|浏览(121)

我谷歌了一下
如何从整数生成MD5哈希(32/64字符)?
我得到的是,有一些例子,可以从字符串或者字节数组中,生成MD5散列字符串,但是在我的例子中,我需要一个整数的MD5散列。
我知道GetHashCode()方法是用来获取整数的散列码的,但是这个方法不适用于我的例子。
我是否需要将整数转换为字符串或字节数组以获得预期的MD5散列字符串?

hrysbysz

hrysbysz1#

大概是这样的

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);
f4t66c6m

f4t66c6m2#

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

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

gopyfrb33#

首先你需要把整数转换成字节数组,然后你可以这样做:

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

fjnneemd4#

谢谢大家。在参考了所有的答案后,我在这里贴出我的答案,它包含了从整数/字符串/字节数组生成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();
        }
    }
}

修改/任何更好的解决方案,这段代码总是受欢迎的。

wlp8pajw

wlp8pajw5#

你可以试试这个,

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

相关问题