create a sha1 hash from a string in csharp

To create a SHA1 hash from a string in C#, you can use the SHA1CryptoServiceProvider 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 input = "Hello world!";
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);

        using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
        {
            byte[] hashedBytes = sha1.ComputeHash(inputBytes);
            string hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
            Console.WriteLine(hash);
        }
    }
}
525 chars
20 lines

In this example, we first convert the input string to its UTF-8 encoded byte representation using the Encoding.UTF8.GetBytes() method. Then, we create a new instance of the SHA1CryptoServiceProvider class and use its ComputeHash() method to compute the SHA1 hash of the input bytes. Finally, we convert the hashed bytes to a string representation using BitConverter.ToString(), replace the hyphens with empty strings using the string.Replace() method, and convert the result to lowercase using the string.ToLower() method. The resulting hash is output to the console.

Output:

main.cs
2ef7bde608ce5404e97d5f042f95f89f1c232871
41 chars
2 lines

gistlibby LogSnag