与C#等效的MessageDigest代码

avatar
作者
猴君
阅读量:2

以下是使用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 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!