Generate SHA-512 hash for the input data in C#
This post will discuss how to generate the SHA512 hash for the input data in C#.
We can use the SHA512 class to compute the SHA512 hash. To compute the SHA512 hash value of a string, first initialize a SHA512 hash object using the SHA512.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, convert the byte array to a 128-character, hexadecimal-formatted string. This approach is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Text; using System.Security.Cryptography; public class Example { static string ComputeSHA512(string s) { StringBuilder sb = new StringBuilder(); using (SHA512 sha512 = SHA512.Create()) { byte[] hashValue = sha512.ComputeHash(Encoding.UTF8.GetBytes(s)); foreach (byte b in hashValue) { sb.Append($"{b:X2}"); } } return sb.ToString(); } public static void Main() { string hashValue = ComputeSHA512("Some string"); Console.WriteLine(hashValue); } } |
Output:
31FCBF83B5BA1C6A378A46645558A961FFB94FBB61F502D2F3BECB12FEAE63D9433851E8B83EA56D143BDFFC83874DB881F8E5E6AC2FC787ED628D4E7E7BF6F0
On .NET 5 and above, we can use the Convert.ToHexString() method to convert the byte array to its equivalent string representation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Text; using System.Security.Cryptography; public class Example { static string ComputeSHA512(string s) { using (SHA512 sha512 = SHA512.Create()) { byte[] hashValue = sha512.ComputeHash(Encoding.UTF8.GetBytes(s)); return Convert.ToHexString(hashValue); } } public static void Main() { string hashValue = ComputeSHA512("Some string"); Console.WriteLine(hashValue); } } |
Output:
31FCBF83B5BA1C6A378A46645558A961FFB94FBB61F502D2F3BECB12FEAE63D9433851E8B83EA56D143BDFFC83874DB881F8E5E6AC2FC787ED628D4E7E7BF6F0
That’s all about generating the SHA512 hash for the input data in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)