温馨提示×

与C#等效的MessageDigest代码

c#
小云
108
2023-09-27 08:18:38
栏目: 编程语言

以下是使用C#编写的与MessageDigest等效的代码:

using System.Security.Cryptography;
using System.Text;
public class MessageDigest
{
public static string GetSHA1(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha1.ComputeHash(bytes);
return ConvertToHex(hashBytes);
}
}
public static string GetMD5(string input)
{
using (MD5 md5 = MD5.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(bytes);
return ConvertToHex(hashBytes);
}
}
private static string ConvertToHex(byte[] bytes)
{
StringBuilder hexBuilder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
hexBuilder.Append(bytes[i].ToString("x2"));
}
return hexBuilder.ToString();
}
}

可以使用MessageDigest.GetSHA1(input)方法来获取输入字符串的SHA-1哈希值,使用MessageDigest.GetMD5(input)方法来获取输入字符串的MD5哈希值。

示例用法:

string input = "Hello World";
string sha1Hash = MessageDigest.GetSHA1(input);
string md5Hash = MessageDigest.GetMD5(input);
Console.WriteLine("SHA-1 Hash: " + sha1Hash);
Console.WriteLine("MD5 Hash: " + md5Hash);

输出:

SHA-1 Hash: 0a4d55a8d778e5022fab701977c5d840bbc486d0
MD5 Hash: ed076287532e86365e841e92bfc50d8c

0