namespace ZelWiki.Security
{
///
///
///
public class Crc32
{
#region
///
/// 逆CRC32算法的生成多项式(模2)
///
private const UInt32 s_generator = 0xEDB88320;
#endregion
#region
///
/// 创建Crc32类的新实例
///
public Crc32()
{
m_checksumTable = Enumerable.Range(0, 256).Select(i =>
{
var tableEntry = (uint)i;
for (var j = 0; j < 8; ++j)
{
tableEntry = ((tableEntry & 1) != 0)
? (s_generator ^ (tableEntry >> 1))
: (tableEntry >> 1);
}
return tableEntry;
}).ToArray();
}
#endregion
#region
///
/// 计算字节流的校验和
///
///
///
///
///
public UInt32 Get(IEnumerable byteStream)
{
try
{
return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>
(m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^
(checksumRegister >> 8)));
}
catch (FormatException e)
{
throw new Exception("无法以字节形式读取流", e);
}
catch (InvalidCastException e)
{
throw new Exception("无法以字节形式读取流", e);
}
catch (OverflowException e)
{
throw new Exception("无法以字节形式读取流", e);
}
}
#endregion
#region
///
/// 包含计算校验和块的缓存
///
private readonly UInt32[] m_checksumTable;
#endregion
}
}