How to create a SHA256 hash of a loaded text file

I have a project where I get the URL of a file (e.g. www.documents.com/docName.txt) and I want to create a hash for this 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 he uses filestream, he uses files stored on his hard drive (for example, c: /documents/docName.txt). But I need it to work with the URL of the file, not the file on disk.

+4
source share
2 answers

To download a 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:

 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(); 
+4
source

You might want to try something similar, although other options may be better depending on the application (and the existing infrastructure) that actually does the hashing. Also, I assume that you really do not want to download and store files locally.

 public static class FileHasher { /// <summary> /// Gets a files' contents from the given URI and calculates the SHA256 hash /// </summary> public static byte[] GetFileHash(Uri FileUri) { using (var Client = new WebClient()) { return SHA256Managed.Create().ComputeHash(Client.OpenRead(FileUri)); } } } 
+1
source

Source: https://habr.com/ru/post/1499819/


All Articles