Tuesday, May 7, 2013

Find SHA256 value of a File in CSharp (C#)


Use the below code to find the SHA256 value of a file. When the user clicks the btn_Generate_Click button the SHA256 value will be generated and displayed in a RichTextBox.
C# Code:
  1. private void btn_Generate_Click(object sender, EventArgs e)
  2. {
  3. hashOfFile("ENTER THE FILE PATH TO FIND SHA256");
  4. }
  1. public void hashOfFile(string fileToHash)
  2. {
  3. FileStream rdr = default(FileStream);
  4. SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
  5. byte[] bytes = null;
  6. string rtn = "";
  7.  
  8. if (File.Exists(fileToHash))
  9. {
  10. rdr = new FileStream(fileToHash, FileMode.Open, FileAccess.Read);
  11. bytes = sha.ComputeHash(rdr);
  12. rtn = ByteArrayToString(bytes);
  13. }
  14.  
  15. richTextBox1.Text=rtn;
  16. }
  1. private string ByteArrayToString(byte[] arrInput)
  2. {
  3. System.Text.StringBuilder sb = new System.Text.StringBuilder(arrInput.Length * 2);
  4. for (int i = 0; i <= arrInput.Length - 1; i++)
  5. {
  6. sb.Append(arrInput[i].ToString("X2"));
  7. }
  8. return sb.ToString().ToLower();
  9. }

No comments:

Post a Comment