C# 生成字符串的 CheckSum

C# 生成字符串的 CheckSum

private static string CheckSum(string message)
{
    char[] chars = message.ToCharArray();
    int checksum = 0;
    for (int i = 0; i < chars.Length; i++)
    {
        checksum += (int)chars[i];
    }
    checksum = (~checksum & 0xFFFF) + 0x0001;
    return Convert.ToString(checksum, 16).ToUpper();
}

例如,字符串“1234567890” 的 CheckSum 为:“FDF3”

C#中,可以使用不同的算法来计算数据的校验和。以下是一些常见的校验和算法示例: 1. CRC32校验和: ```csharp using System; using System.Security.Cryptography; public static class ChecksumHelper { public static uint CalculateCRC32(byte[] data) { using (var crc32 = new CRC32()) { return crc32.ComputeHash(data); } } } public class CRC32 : HashAlgorithm { private const uint Polynomial = 0xEDB88320; private uint[] table; private uint crc; public CRC32() { table = InitializeTable(Polynomial); crc = 0xffffffff; } public override void Initialize() { crc = 0xffffffff; } protected override void HashCore(byte[] array, int ibStart, int cbSize) { crc ^= 0xffffffff; for (int i = ibStart; i < ibStart + cbSize; i++) { crc = (crc >> 8) ^ table[array[i] ^ crc & 0xff]; } crc ^= 0xffffffff; } protected override byte[] HashFinal() { byte[] hash = new byte[4]; hash[0] = (byte)((crc >> 24) & 0xff); hash[1] = (byte)((crc >> 16) & 0xff); hash[2] = (byte)((crc >> 8) & 0xff); hash[3] = (byte)(crc & 0xff); return hash; } private static uint[] InitializeTable(uint polynomial) { uint[] table = new uint[256]; for (uint i = 0; i < 256; i++) { uint entry = i; for (int j = 0; j < 8; j++) { if ((entry & 1) == 1) { entry = (entry >> 1) ^ polynomial; } else { entry >>= 1; } } table[i] = entry; } return table; } } ``` 使用示例: ```csharp byte[] data = { 0x01, 0x02, 0x03, 0x04 }; uint crc32Checksum = ChecksumHelper.CalculateCRC32(data); Console.WriteLine($"CRC32 checksum: 0x{crc32Checksum:X8}"); ``` 2. MD5校验和: ```csharp using System; using System.Security.Cryptography; using System.Text; public static class ChecksumHelper { public static string CalculateMD5(string input) { using (var md5 = MD5.Create()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("X2")); } return sb.ToString(); } } } ``` 使用示例: ```csharp string input = "Hello, world!"; string md5Checksum = ChecksumHelper.CalculateMD5(input); Console.WriteLine($"MD5 checksum: {md5Checksum}"); ``` 这些示例展示了如何在C#中计算CRC32和MD5校验和。根据你的需求,你可以选择适合的校验和算法来计算数据的校验和。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值