Reputation: 2195
I have a website that allows users to upload files which are in turn stored in a Microsoft SQL Database.
The database contains hundreds of thousands of images and is becoming unmanagable. As such I've written a powershell script that extracts those images from the database to the filesystem and then generates a SHA1 hash of the file as such:
$SHA1 = Get-Checksum -Algorithm sha1 -File ($Dest + "$i.jpg")
Going forward I no longer want to store images in the database but rather use the file system however I still need to generate SHA1 hashes of each file.
I've been unable to find any documentation on generating SHA1 file hashes in classic asp or asp.net (c# or vb.net).
Note I specifically need to know how to generate FILE HASHES - not hashes of strings.
Has anyone else done this or know if or how it can be done? Any example code you could provide would be greatly appreciated.
Thanks Brad
Upvotes: 2
Views: 2859
Reputation: 1798
using (FileStream fs = new FileStream(@"C:\file\location", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
using (SHA1Managed sha1 = new SHA1Managed())
{
byte[] hash = sha1.ComputeHash(bs);
StringBuilder formatted = new StringBuilder(2 * hash.Length);
foreach (byte b in hash)
{
formatted.AppendFormat("{0:X2}", b);
}
}
}
formatted
contains the string representation of the SHA-1 hash. Also, by using a FileStream
instead of a byte buffer, ComputeHash
computes the hash in chunks, so you don't have to load the entire file in one go, which is helpful for large files.
Answer borrowed from mgbowen
in How do I do a SHA1 File Checksum in C#?
Upvotes: 1