Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SHA-2 (512) Base64 encoded hash

Tags:

c#

encryption

Looking for a way to do the following in C# from a string.

public static String sha512Hex(byte[] data)

Calculates the SHA-512 digest and returns the value as a hex string.

Parameters: data - Data to digest Returns: SHA-512 digest as a hex string

    private static string GetSHA512(string text)
    {
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(text);
        SHA512Managed hashString = new SHA512Managed();
        string encodedData = Convert.ToBase64String(message);
        string hex = "";
        hashValue = hashString.ComputeHash(UE.GetBytes(encodedData));
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }
like image 565
Tom S Avatar asked Apr 14 '11 15:04

Tom S


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


1 Answers

Would System.Security.Cryptography.SHA512 be what you need?

var alg = SHA512.Create();
alg.ComputeHash(Encoding.UTF8.GetBytes("test"));
BitConverter.ToString(alg.Hash).Dump();

Executed in LINQPad produces:

EE-26-B0-DD-4A-F7-E7-49-AA-1A-8E-E3-C1-0A-E9-92-3F-61-89-80-77-2E-47-3F-88-19-A5-D4-94-0E-0D-B2-7A-C1-85-F8-A0-E1-D5-F8-4F-88-BC-88-7F-D6-7B-14-37-32-C3-04-CC-5F-A9-AD-8E-6F-57-F5-00-28-A8-FF

To create the method from your question:

public static string sha512Hex(byte[] data)
{
    using (var alg = SHA512.Create())
    {
        alg.ComputeHash(data);
        return BitConverter.ToString(alg.Hash);
    }
}
like image 103
Lasse V. Karlsen Avatar answered Sep 18 '22 06:09

Lasse V. Karlsen