Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create SHA256 hash of downloaded text file

I have a project where I get the url to a file (e.g. www.documents.com/docName.txt) and I want to create a hash for that file. How can I do this.

FileStream filestream;
SHA256 mySHA256 = SHA256Managed.Create();

filestream = new FileStream(docUrl, FileMode.Open);

filestream.Position = 0;

byte[] hashValue = mySHA256.ComputeHash(filestream);

Label2.Text = BitConverter.ToString(hashValue).Replace("-", String.Empty);

filestream.Close();

This is the code i have to create a hash. But seeing how it uses filestream it uses files stored on the hard drive (e.g. c:/documents/docName.txt) But i need it to work with an url to a file and not the path to a file on the drive.

like image 231
Marijn Avatar asked Mar 23 '23 14:03

Marijn


1 Answers

To download the file use:

string url = "http://www.documents.com/docName.txt";
string localPath = @"C://Local//docName.txt"

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, localPath);
}

then read the file like you have:

FileStream filestream;
SHA256 mySHA256 = SHA256Managed.Create();

filestream = new FileStream(localPath, FileMode.Open);

filestream.Position = 0;

byte[] hashValue = mySHA256.ComputeHash(filestream);

Label2.Text = BitConverter.ToString(hashValue).Replace("-", String.Empty);

filestream.Close();
like image 143
Sam Leach Avatar answered Apr 01 '23 10:04

Sam Leach