Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing with SHA1 Algorithm in C#

I want to hash given byte[] array with using SHA1 Algorithm with the use of SHA1Managed.
The byte[] hash will come from unit test.
Expected hash is 0d71ee4472658cd5874c5578410a9d8611fc9aef (case sensitive).

How can I achieve this?

public string Hash(byte [] temp) {     using (SHA1Managed sha1 = new SHA1Managed())     {      } } 
like image 410
Merve Kaya Avatar asked Jun 25 '13 08:06

Merve Kaya


People also ask

Is SHA-1 an algorithm?

In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographically broken but still widely used hash function which takes an input and produces a 160-bit (20-byte) hash value known as a message digest – typically rendered as a hexadecimal number, 40 digits long.

Is SHA a hashing algorithm?

SHA stands for secure hashing algorithm. SHA is a modified version of MD5 and used for hashing data and certificates. A hashing algorithm shortens the input data into a smaller form that cannot be understood by using bitwise operations, modular additions, and compression functions.

Is SHA-1 () a secure method for hashing data?

SHA-1 is now considered insecure since 2005. Major tech giants browsers like Microsoft, Google, Apple and Mozilla have stopped accepting SHA-1 SSL certificates by 2017. To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.


1 Answers

For those who want a "standard" text formatting of the hash, you can use something like the following:

static string Hash(string input) {     using (SHA1Managed sha1 = new SHA1Managed())     {         var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));         var sb = new StringBuilder(hash.Length * 2);          foreach (byte b in hash)         {             // can be "x2" if you want lowercase             sb.Append(b.ToString("X2"));         }          return sb.ToString();     } } 

This will produce a hash like 0C2E99D0949684278C30B9369B82638E1CEAD415.

Or for a code golfed version:

static string Hash(string input) {     var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input));     return string.Concat(hash.Select(b => b.ToString("x2"))); } 
like image 54
Mitch Avatar answered Sep 28 '22 13:09

Mitch