如何计算字符串的CRC32?

51

我该如何在.NET中计算字符串的CRC32(循环冗余校验和)?

4个回答

43

这位先生看起来可以回答你的问题。

https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net

以防万一博客消失或链接失效,这里是Github链接:

https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs


从博客文章中使用 Crc32 类的方法:

Crc32 crc32 = new Crc32();
String hash = String.Empty;

using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
  foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();

Console.WriteLine("CRC-32 is {0}", hash);

1
好的答案,那个链接里的代码看起来很不错。谢谢Pete! - Erick Brown
这段代码似乎已经失效了。Crc32类没有基础构造函数,而他的代码示例却调用了它。 - mellis481
7
有一个 NuGet 包可以为你处理这个问题,安装命令是 Install-Package Crc32.NET。它实际上实现了这个算法(并且声称比其他替代品要快得多)。你可以运行上面的 NuGet 命令或在 GitHub 上找到源代码 https://github.com/force-net/Crc32.NET。我通常不建议为每一个小事情都包含依赖项,但这似乎是一种专门的、合理的情况。 - Pete

14

由于您似乎想计算字符串的CRC32(而不是文件),这里有一个很好的例子:https://rosettacode.org/wiki/CRC-32#C.23

代码如下,以防它消失:

/// <summary>
/// Performs 32-bit reversed cyclic redundancy checks.
/// </summary>
public class Crc32
{
    #region Constants
    /// <summary>
    /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm. 
    /// </summary>
    private const UInt32 s_generator = 0xEDB88320;
    #endregion

    #region Constructors
    /// <summary>
    /// Creates a new instance of the Crc32 class.
    /// </summary>
    public Crc32()
    {
        // Constructs the checksum lookup table. Used to optimize the checksum.
        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 Methods
    /// <summary>
    /// Calculates the checksum of the byte stream.
    /// </summary>
    /// <param name="byteStream">The byte stream to calculate the checksum for.</param>
    /// <returns>A 32-bit reversed checksum.</returns>
    public UInt32 Get<T>(IEnumerable<T> byteStream)
    {
        try
        {
            // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.
            return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => 
                      (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));
        }
        catch (FormatException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
        catch (InvalidCastException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
        catch (OverflowException e)
        {
            throw new CrcException("Could not read the stream out as bytes.", e);
        }
    }
    #endregion

    #region Fields
    /// <summary>
    /// Contains a cache of calculated checksum chunks.
    /// </summary>
    private readonly UInt32[] m_checksumTable;

    #endregion
}

并使用它:

var arrayOfBytes = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog");

var crc32 = new Crc32();
Console.WriteLine(crc32.Get(arrayOfBytes).ToString("X"));

您可以在此处测试输入/输出值:https://crccalc.com/


2
使用前面答案中的逻辑,这是我的看法:
public class CRC32
{
    private readonly uint[] ChecksumTable;
    private readonly uint Polynomial = 0xEDB88320;

    public CRC32()
    {
        ChecksumTable = new uint[0x100];

        for (uint index = 0; index < 0x100; ++index)
        {
            uint item = index;
            for (int bit = 0; bit < 8; ++bit)
                item = ((item & 1) != 0) ? (Polynomial ^ (item >> 1)) : (item >> 1);
            ChecksumTable[index] = item;
        }
    }

    public byte[] ComputeHash(Stream stream)
    {
        uint result = 0xFFFFFFFF;

        int current;
        while ((current = stream.ReadByte()) != -1)
            result = ChecksumTable[(result & 0xFF) ^ (byte)current] ^ (result >> 8);

        byte[] hash = BitConverter.GetBytes(~result);
        Array.Reverse(hash);
        return hash;
    }

    public byte[] ComputeHash(byte[] data)
    {
        using (MemoryStream stream = new MemoryStream(data))
            return ComputeHash(stream);
    }
}

1
Crc32在.NET平台扩展中得到支持。 要使用它,您需要先安装NuGet包。
要计算字符串的Crc32值,您需要将其转换为字节数组。使用哪种编码取决于字符串的来源。
var text = "target string";
var crc32 = new System.IO.Hashing.Crc32();
var bytes = Encoding.UTF8.GetBytes(text);
crc32.Append(bytes);

计算结果默认为小端序,如果需要转换为大端序,可以反转结果数组:

var checkSum = crc32.GetCurrentHash();
// to Big Endian
Array.Reverse(checkSum);

最后,输出可以是数字或十六进制,根据您的需要。
// int
Console.WriteLine(BitConverter.ToInt32(checkSum));
// lowercase hex string
Console.WriteLine(BitConverter.ToString(checkSum).Replace("-", "").ToLower());

这是唯一一个解释如何使用官方.NET包的答案,我认为应该标记为正确答案。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接