create a sha256 hash from a string in csharp

To create a SHA256 hash from a string in C#, you can use the SHA256Managed class from the System.Security.Cryptography namespace. Here's an example:

main.cs
using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string myString = "Hello, world!";
        byte[] bytes = Encoding.UTF8.GetBytes(myString);
        
        SHA256 sha256 = SHA256Managed.Create();
        byte[] hash = sha256.ComputeHash(bytes);
        
        Console.WriteLine(Convert.ToBase64String(hash));
    }
}
408 chars
18 lines

In this example, we first convert a string to a byte array using the UTF-8 encoding. We then create a SHA256Managed object and use the ComputeHash method to create a SHA256 hash from the byte array. Finally, we convert the hash to a base64-encoded string and write it to the console.

Note that this is just one example of how to create a SHA256 hash in C#. There are other ways to do it, depending on your specific requirements.

gistlibby LogSnag