1. If you want to get the SHA256 of a string , the code is as follows:
public static string SHA256 (String str) { //If STR has Chinese, different encoding sha is different!! byte[] sha256data = Encoding.UTF8.GetBytes (str); SHA256Managed Sha256 = new sha256managed (); byte[] by = Sha256.computehash (sha256data); Return Bitconverter.tostring (by). Replace ("-", ""). ToLower (); //return convert.tobase64string (by); /+ }
2. If you want to get the SHA256 of a file , the code is as follows:
public string SHA256 () { string str = @ "C:\Users\ICCWDT_Driver\iccwdt.sys"; FileStream stream = new FileStream (str, filemode.open); SHA256Managed Sha256 = new sha256managed (); byte[] by = Sha256.computehash (stream); Return Bitconverter.tostring (by). Replace ("-", ""). ToLower (); //return convert.tobase64string (by); /+ }
3. By looking at the system's APIs, you can see that there are two parameters that can be passed in: Incoming byte[] type or stream type
Summary: // computes the hash value of the specified byte array. //// parameter: // buffer: // input to calculate its hash code. //// Returns the result: // computed hash code. //// Exception:/ / System.ArgumentNullException: // buffer is null. //// system.objectdisposedexception: // This object has been disposed. Public byte[] ComputeHash (byte[] buffer); //Summary: // calculates the hash value of the specified System.IO.Stream object. //// parameter: // InputStream: // input to calculate its hash code. //// Returns the result: // computed hash code. //// Exception: // system.objectdisposedexception: // This object has been disposed. Public byte[] ComputeHash (Stream inputstream);
C # get SHA256 code