Lựa chọn

 Danh mục

 Chi tiết tài nguyên
Cyclic Redundancy Check (CRC32) HashAlgorithm
   Đăng bởi: host | Ngày : 01:43 05/12/09 | Xem: 529 |        
 
Cyclic Redundancy Check (CRC32) HashAlgorithm
Caution
As Paul Ravier mentioned, this class should NOT be used for security purposes. The CRC32 algorithm can easily be brute forced in minutes. For security applications use MD5, SHA1, SHA256, SHA384, or SHA512 in the System.Security.Cryptography namespace.
Introduction
The System.Security.Cryptography contains the HashAlgorithm. The HashAlgorithm class represents the base class from which all implementations of cryptographic hash algorithms must derive. Although I don't believe the Cyclic Redundancy Check algorithm is considered a true cryptographic hash algorithm, it does fit into the HashAlgorithm pattern.
The CRC32 algorithm is initialized using a 32-bit unsigned integer. This unsigned integer is known the polynomial. Different polynomials produce different check sums. The polynomial is used to generate a 256 element table that speeds the calculation. Normal applications will use the same polynomial throughout it's life-time. Due to this, the default behavior of the CRC32 class caches the table on first use. This behavior can be changed by setting the AutoCache property to false
Sample Usage
// Generic function using HashAlgorithm 
public void HashData(HashAlgorithm hashAlg, string str )
{
    byte[] rawBytes = System.Text.ASCIIEncoding.ASCII.GetBytes( str );
    byte[] hashData = hashAlg.ComputeHash( rawBytes );
    Console.WriteLine( BitConverter.ToString( hashData ) );
}
 
// Example showing that both functions can be used
public void Example()
{
    string str = "A lazy brown dog..."; // data to hash
 
    MD5 md5 = new MD5CryptoServiceProvider();
    HashData( md5, str); // Sample of the MD5 algorithm 
 
    CRC32 crc = new CRC32(); // equivalent to new CRC32(CRC32.DefaultPolynomial);
    HashData( crc, str); // Compute the default CRC32 value for a string
}
Conclusion
Although the MD5, SHA1, SHA256, SHA384, and SHA512 are more accurate than the CRC32 algorithm, sometimes you do not have a choice due various reasons. This class can be used without modification anywhere other HashAlgorithm classes can.
 
Bình luận

Thêm nhận xét