阅读量:0
在C#中,没有现成的库可以直接生成校验和(checksum),但你可以使用.NET内置的类和方法来计算校验和
using System; using System.Security.Cryptography; using System.Text; public class ChecksumHelper { public static string CalculateMD5(string input) { using (var md5 = MD5.Create()) { var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } public static string CalculateSHA1(string input) { using (var sha1 = SHA1.Create()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } public static string CalculateSHA256(string input) { using (var sha256 = SHA256.Create()) { var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(input)); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } }
这个示例中包含了三个方法:CalculateMD5
、CalculateSHA1
和CalculateSHA256
,分别用于计算字符串的MD5、SHA1和SHA256校验和。你可以根据需要选择合适的方法来计算校验和。
使用示例:
string input = "Hello, world!"; string md5Checksum = ChecksumHelper.CalculateMD5(input); string sha1Checksum = ChecksumHelper.CalculateSHA1(input); string sha256Checksum = ChecksumHelper.CalculateSHA256(input); Console.WriteLine($"MD5: {md5Checksum}"); Console.WriteLine($"SHA1: {sha1Checksum}"); Console.WriteLine($"SHA256: {sha256Checksum}");
这将输出:
MD5: 65a8e27d8879283831b664bd8b7f0ad4 SHA1: 2ef7bde608ce5404e97d5f042f95f89f1c232871 SHA256: 7509e5bda0c762d2bac7f90d758b5b2263fa01ccbc542ab5e3df163be08e6ca9