C# hashes

橙三吉。 提交于 2020-01-02 03:28:26

问题


I'm new to C#

  1. How do i hash files with C#
  2. What is available ? (md5, crc, sha1, etc)
  3. Is there an interface i should inherit?

Basically i want to checksum multiple files and store it in a db along with using two of my own checksums/hashes.


回答1:


1.) How do i hash files with C#?

You can utilize .NET classes under System.Security.Cryptography

2.) What is available?

  • KeyedHashAlgorithm
  • MD5
  • RIPEMD160
  • SHA1
  • SHA256
  • SHA384
  • SHA512

3.) Is there an interface i should inherit?

No you don't have to. Take a look at HashAlgorithm.Create(...)




回答2:


Snippet

byte[] result; 
SHA1 sha = new SHA1CryptoServiceProvider(); 
using(FileStream fs = File.OpenRead(@"file.txt"))
{
   result = sha.ComputeHash(fs);
}

See also SHA1CryptoServiceProvider or MD5CryptoServiceProvider.

CRC is not available -- it's more efficient to create your own.




回答3:


What are you trying to achieve with the hashes? If you're trying to actually guarantee that nobody maliciously altered the files, please don't implement your own checksum or hash. You'll probably make some mistake and someone will be able to tamper with a file and have the checksums still match. Use a good hash function like SHA-256.



来源:https://stackoverflow.com/questions/622900/c-sharp-hashes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!