Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MessageDigest class in C#

Tags:

c#

encryption

I require a certain piece of encryption logic done in Java to be converted to C#

What would be the C# equivalent for the MessageDigest update , Digest and reset functions ?

like image 384
siva Avatar asked Mar 18 '13 06:03

siva


People also ask

What is import Java security MessageDigest?

Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. A MessageDigest object starts out initialized. The data is processed through it using the update methods. At any point reset can be called to reset the digest.

Is MessageDigest thread safe?

MessageDigest is not thread safe and for the same input, it can generate different hash #816.

What is meant by MessageDigest give an example?

A message digest is a fixed size numeric representation of the contents of a message, computed by a hash function. A message digest can be encrypted, forming a digital signature. Messages are inherently variable in size. A message digest is a fixed size numeric representation of the contents of a message.


2 Answers

In C#, the class is HashAlgorithm.

The equivalent to update is either TransformBlock(...) or TransformFinalBlock(...), after the final block version is called (you can also use an empty input) you can call the Hash property that will give you the digest value.

HashAlgorithm is likely to be reusable after final block is called (which means it is reset for the next time you call TransformBlock), you can double check if your HashAlgorithm supports reusing at all by checking the property CanReuseTransform.

The equivalent to your reset()/digest() combo is a one line byte[] ComputeHash(byte[]).

like image 178
jbtule Avatar answered Sep 27 '22 16:09

jbtule


try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      md.update(password.getBytes());
      BigInteger hash = new BigInteger(1, md.digest());
      hashword = hash.toString(16);
} catch (NoSuchAlgorithmException ex) {
      /* error handling */
}
return hashword;
public static string HashPassword(string input)
{
    var sha1 = SHA1Managed.Create();
    byte[] inputBytes = Encoding.ASCII.GetBytes(input);
    byte[] outputBytes = sha1.ComputeHash(inputBytes);
    return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
}
like image 34
chinhiyoshi Avatar answered Sep 27 '22 17:09

chinhiyoshi