在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計算。