从字符串计算MD5哈希值

use*_*847 115 c# md5

我使用以下C#代码从字符串计算MD5哈希.它运行良好,生成一个32个字符的十六进制字符串,如下所示: 900150983cd24fb0d6963f7d28e17f72

string sSourceData;
byte[] tmpSource;
byte[] tmpHash;
sSourceData = "MySourceData";

//Create a byte array from source data.
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);

// and then convert tmpHash to string...
Run Code Online (Sandbox Code Playgroud)

有没有办法使用这样的代码生成一个16个字符的十六进制字符串(或12个字符的字符串)?一个32个字符的十六进制字符串是好的,但我认为客户输入代码是无聊的!

Ana*_*bhi 166

根据MSDN

创建MD5:

   public static string CreateMD5(string input)
    {
        // Use input string to calculate MD5 hash
        using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
        {
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 来源:https://msdn.microsoft.com/en-us/library/system.security.cryptography.md5%28v=vs.110%29.aspx (9认同)
  • 通常,您应该散列无损文本编码,如UTF8. (5认同)
  • 如果您从某处复制/粘贴,则应始终说出从哪里获得代码,否则将其归类为窃。 (4认同)
  • @PrashantPimpale MD5是摘要算法。可以把它想象成将牛变成牛排。 (4认同)
  • 微软[说](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1850)“使用静态 HashData 方法比创建和管理HashAlgorithm 实例调用 ComputeHash”。示例:“MD5.HashData(字节)” (2认同)

Mic*_*ael 88

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you want
Run Code Online (Sandbox Code Playgroud)

  • 我的答案不是表示最佳做法.在上下文中提供了OP提出他的问题.如果OP已经询问使用什么是最合适的散列算法,答案可能会有所不同(相应地). (12认同)
  • 对于一个超过两年的线程,我赞赏对某些内容不合时宜的投票.;) (7认同)

cra*_*nch 10

尝试使用LINQ创建MD5哈希的字符串表示,但是,没有一个答案是LINQ解决方案,因此将其添加到可用解决方案的大杂烩中.

string result;
using (MD5 hash = MD5.Create())
{
    result = String.Join
    (
        "",
        from ba in hash.ComputeHash
        (
            Encoding.UTF8.GetBytes(observedText)
        ) 
        select ba.ToString("x2")
    );
}
Run Code Online (Sandbox Code Playgroud)

  • 单行,方法语法:`return string.Join( "", hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x =&gt; x.ToString("x2") ) );` (2认同)
  • ...在这种情况下,我建议改为`return string.Concat( hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x =&gt; x.ToString("x2") ) );`。它更短一些,意图可能更清晰,并且执行速度稍快(&lt;10% 性能提升)。 (2认同)

Kin*_*nus 8

完全取决于您想要实现的目标.从技术上讲,您可以从MD5哈希的结果中获取前12个字符,但MD5的规范是生成32个字符.

减小散列的大小会降低安全性,并增加冲突和系统崩溃的可能性.

也许如果你让我们更多地了解你想要实现的目标,我们可能会提供更多帮助.


L.B*_*L.B 8

您可以使用Convert.ToBase64String将MD5的16字节输出转换为~24字符串.在不降低安全性的情况下更好一点.(j9JIbSY8HuT89/pwdC8jlw==为你的例子)

  • 一个不错的解决方法,但是我怀疑他的OP是否希望区分大小写并使用特殊字符。 (2认同)

O T*_*Ldt 8

public static string Md5(string input, bool isLowercase = false)
{
    using (var md5 = MD5.Create())
    {
        var byteHash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
        var hash = BitConverter.ToString(byteHash).Replace("-", "");
        return (isLowercase) ? hash.ToLower() : hash;
    }
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*bes 6

我想最好在字符串 MD5 中使用 UTF-8 编码。

public static string MD5(this string s)
{
    using (var provider = System.Security.Cryptography.MD5.Create())
    {
        StringBuilder builder = new StringBuilder();                           

        foreach (byte b in provider.ComputeHash(Encoding.UTF8.GetBytes(s)))
            builder.Append(b.ToString("x2").ToLower());

        return builder.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)


Thi*_*Big 5

支持字符串和文件流.

例子

string hashString = EasyMD5.Hash("My String");

string hashFile = EasyMD5.Hash(System.IO.File.OpenRead("myFile.txt"));
Run Code Online (Sandbox Code Playgroud)

-

   class EasyMD5
        {
            private static string GetMd5Hash(byte[] data)
            {
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                    sBuilder.Append(data[i].ToString("x2"));
                return sBuilder.ToString();
            }

            private static bool VerifyMd5Hash(byte[] data, string hash)
            {
                return 0 == StringComparer.OrdinalIgnoreCase.Compare(GetMd5Hash(data), hash);
            }

            public static string Hash(string data)
            {
                using (var md5 = MD5.Create())
                    return GetMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)));
            }
            public static string Hash(FileStream data)
            {
                using (var md5 = MD5.Create())
                    return GetMd5Hash(md5.ComputeHash(data));
            }

            public static bool Verify(string data, string hash)
            {
                using (var md5 = MD5.Create())
                    return VerifyMd5Hash(md5.ComputeHash(Encoding.UTF8.GetBytes(data)), hash);
            }

            public static bool Verify(FileStream data, string hash)
            {
                using (var md5 = MD5.Create())
                    return VerifyMd5Hash(md5.ComputeHash(data), hash);
            }
        }
Run Code Online (Sandbox Code Playgroud)


Bra*_*d M 5

此解决方案需要 c# 8 并利用Span<T>. 请注意,如有必要,您仍然需要调用.Replace("-", string.Empty).ToLowerInvariant()以格式化结果。

public static string CreateMD5(ReadOnlySpan<char> input)
{
    var encoding = System.Text.Encoding.UTF8;
    var inputByteCount = encoding.GetByteCount(input);
    using var md5 = System.Security.Cryptography.MD5.Create();

    Span<byte> bytes = inputByteCount < 1024
        ? stackalloc byte[inputByteCount]
        : new byte[inputByteCount];
    Span<byte> destination = stackalloc byte[md5.HashSize / 8];

    encoding.GetBytes(input, bytes);

    // checking the result is not required because this only returns false if "(destination.Length < HashSizeValue/8)", which is never true in this case
    md5.TryComputeHash(bytes, destination, out int _bytesWritten);

    return BitConverter.ToString(destination.ToArray());
}
Run Code Online (Sandbox Code Playgroud)


Int*_*Hen 5

我不知道有关 16 个字符的十六进制字符串的任何信息......

using System;
using System.Security.Cryptography;
using System.Text;
Run Code Online (Sandbox Code Playgroud)

但这是我在一行中创建 MD5 哈希值的方法。

string hash = BitConverter.ToString(MD5.Create().ComputeHash(Encoding.ASCII.GetBytes("THIS STRING TO MD5"))).Replace("-","");
Run Code Online (Sandbox Code Playgroud)


Jam*_*orn 5

这是我的实用函数UTF8,可以根据需要替换为ASCII

    public static byte[] MD5Hash(string message)
    {
        return MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(message));
    }
Run Code Online (Sandbox Code Playgroud)