This post will discuss how to generate the SHA-256 hash of a string in C#.

You can use the SHA256 class to compute the SHA-256 hash. To compute the SHA256 hash value of a string, first initialize a SHA256 hash object using the SHA256.Create() method and convert the given string into a byte array with the Encoding.GetBytes() method. Then compute the hash value for the specified byte array using the ComputeHash() method. Finally, you can convert the byte array to a 64-character, hexadecimal-formatted string, as shown below:

Download  Run Code

Output:

185F8DB32271FE25F561A6FC938B2E264306EC304EDA518007D1764826381969

 
Note that SHA256 class requires System.Security.Cryptography namespace. You can also use the SHA256Managed class, but it is obsolete. Using new SHA256Managed() to initialize a SHA256 hash object will result in warning SYSLIB0021: ‘SHA256Managed’ is obsolete: ‘Derived cryptographic types are obsolete. Use the Create method on the base type instead.’. Here’s an even shorter version of the above code that replaces the foreach loop with the BitConverter.ToString() method:

Download  Run Code

Output:

185F8DB32271FE25F561A6FC938B2E264306EC304EDA518007D1764826381969

 
If you’re using .NET 5 and above, you can use the Convert.ToHexString() method to convert the byte array to its equivalent string representation.

Download  Run Code

Output:

185F8DB32271FE25F561A6FC938B2E264306EC304EDA518007D1764826381969

That’s all about generating the SHA-256 hash of a string in C#.