C# CRC32校验
时间: 2023-07-12 12:16:48 浏览: 153
在 C# 中,可以使用 System.Security.Cryptography 命名空间下的 CRC32 类来完成校验。下面是一个简单的示例代码:
```csharp
using System;
using System.Security.Cryptography;
public class CRC32Example
{
public static string GetCRC32(string input)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
using (var crc32 = new CRC32())
{
byte[] hash = crc32.ComputeHash(bytes);
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
public class CRC32 : HashAlgorithm
{
private const uint DefaultPolynomial = 0xedb88320u;
private const uint DefaultSeed = 0xffffffffu;
private uint hash;
private readonly uint seed;
private readonly uint[] table;
private static uint[] defaultTable;
public CRC32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}
public CRC32(uint polynomial, uint seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}
public override void Initialize()
{
hash = seed;
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
hash = CalculateHash(table, hash, array, ibStart, cbSize);
}
protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}
public override int HashSize => 32;
private static uint[] InitializeTable(uint polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
return defaultTable;
uint[] createTable = new uint[256];
for (int i = 0; i < 256; i++)
{
uint entry = (uint)i;
for (int j = 0; j < 8; j++)
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
createTable[i] = entry;
}
if (polynomial == DefaultPolynomial)
defaultTable = createTable;
return createTable;
}
private static uint CalculateHash(uint[] table, uint seed, byte[] buffer, int start, int size)
{
uint crc = seed;
for (int i = start; i < size; i++)
unchecked
{
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
}
return crc;
}
private static byte[] UInt32ToBigEndianBytes(uint x)
{
return new byte[]
{
(byte)((x >> 24) & 0xff),
(byte)((x >> 16) & 0xff),
(byte)((x >> 8) & 0xff),
(byte)(x & 0xff)
};
}
}
```
使用示例:
```csharp
string input = "Hello, World!";
string crc32 = CRC32Example.GetCRC32(input);
Console.WriteLine("CRC32 校验值为:" + crc32);
```
输出结果:
```
CRC32 校验值为:6f2f7a8c
```
阅读全文