在C#中,常用的Checksum算法主要包括以下几种:
Crc32.NET
或自定义实现CRC32算法。using System;
using Crc32; // 引入Crc32.NET库
byte[] data = new byte[] { 0x68, 0x65, 0x6c, 0x6c, 0x6f }; // 示例数据
uint crc = Crc32Algorithm.Compute(data); // 计算CRC32校验值
Console.WriteLine($"CRC32: {crc}");
System.Security.Cryptography
命名空间中的MD5
类实现MD5算法。using System;
using System.Security.Cryptography;
using System.Text;
string input = "hello";
byte[] data = Encoding.UTF8.GetBytes(input);
using (var md5 = MD5.Create())
{
byte[] hash = md5.ComputeHash(data);
string md5Str = BitConverter.ToString(hash).Replace("-", "").ToLower();
Console.WriteLine($"MD5: {md5Str}");
}
System.Security.Cryptography
命名空间中的SHA1
类实现SHA-1算法。using System;
using System.Security.Cryptography;
using System.Text;
string input = "hello";
byte[] data = Encoding.UTF8.GetBytes(input);
using (var sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(data);
string sha1Str = BitConverter.ToString(hash).Replace("-", "").ToLower();
Console.WriteLine($"SHA-1: {sha1Str}");
}
System.Security.Cryptography
命名空间中的SHA256
和SHA512
类实现SHA-256和SHA-512算法。using System;
using System.Security.Cryptography;
using System.Text;
string input = "hello";
byte[] data = Encoding.UTF8.GetBytes(input);
// SHA-256
using (var sha256 = SHA256.Create())
{
byte[] hash = sha256.ComputeHash(data);
string sha256Str = BitConverter.ToString(hash).Replace("-", "").ToLower();
Console.WriteLine($"SHA-256: {sha256Str}");
}
// SHA-512
using (var sha512 = SHA512.Create())
{
byte[] hash = sha512.ComputeHash(data);
string sha512Str = BitConverter.ToString(hash).Replace("-", "").ToLower();
Console.WriteLine($"SHA-512: {sha512Str}");
}
这些算法在C#中都有相应的实现,可以根据实际需求选择合适的算法进行Checksum计算。