Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using MD5.Create and MD5CryptoServiceProvider?

Tags:

c#

.net

hash

md5

In the .NET framework there are a couple of ways to calculate an MD5 hash it seems, however there is something I don't understand;

What is the distinction between the following? What sets them apart from eachother? They seem to produce identical results:

    public static string GetMD5Hash(string str)     {         MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();         byte[] bytes = ASCIIEncoding.Default.GetBytes(str);         byte[] encoded = md5.ComputeHash(bytes);          StringBuilder sb = new StringBuilder();         for (int i = 0; i < encoded.Length; i++)             sb.Append(encoded[i].ToString("x2"));          return sb.ToString();     }      public static string GetMD5Hash2(string str)     {         System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();         byte[] bytes = Encoding.Default.GetBytes(str);         byte[] encoded = md5.ComputeHash(bytes);          StringBuilder sb = new StringBuilder();         for (int i = 0; i < encoded.Length; i++)             sb.Append(encoded[i].ToString("x2"));          return sb.ToString();     } 
like image 443
dreadwail Avatar asked Apr 08 '10 02:04

dreadwail


People also ask

What is MD5CryptoServiceProvider?

The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function that accepts a message of any length as input and returns as output a fixed-length digest value to be used for authenticating the original message.

What is cryptography security?

AesCryptoServiceProvider Class (System.Security.Cryptography) Performs symmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm.


1 Answers

System.Security.Cryptography.MD5.Create() is actually creating a MD5CryptoServiceProvider. That is why you see the same results.

Looking at the definition MD5 is the base class and it's abstract. I'm guessing they added the public create function for ease of use.

public sealed class MD5CryptoServiceProvider : MD5  public abstract class MD5 : HashAlgorithm 

Take a look at the definitions.

MD5 Represents the abstract class from which all implementations of the MD5 hash algorithm inherit.

MD5CryptoServiceProvider Computes the MD5 hash value for the input data using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited.

like image 169
Jason Rowe Avatar answered Sep 20 '22 09:09

Jason Rowe