C# CRC32 算法
时间: 2023-07-12 22:23:33 浏览: 197
CRC32(循环冗余校验)算法是一种常用的数据校验算法,它可以用于检测数据传输过程中是否出现了错误。
在 C# 中,可以使用 System.Security.Cryptography 命名空间下的 CRC32 类来实现 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
```
以上代码实现了一个简单的 CRC32 算法,可以用于计算任意字符串的校验值。
阅读全文