Calculate a MD5 hash from a string
Solution 1
As per MSDN
Create MD5:
public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes); // .NET 5 +
// Convert the byte array to hexadecimal string prior to .NET 5
// StringBuilder sb = new System.Text.StringBuilder();
// for (int i = 0; i < hashBytes.Length; i++)
// {
// sb.Append(hashBytes[i].ToString("X2"));
// }
// return sb.ToString();
}
}
Solution 2
// given, a password in a string
string password = @"1234abcd";
// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
// without dashes
.Replace("-", string.Empty)
// make lowercase
.ToLower();
// encoded contains the hash you want
Solution 3
Was trying to create a string representation of MD5 hash using LINQ, however, none of the answers were LINQ solutions, therefore adding this to the smorgasbord of available solutions.
string result;
using (MD5 hash = MD5.Create())
{
result = String.Join
(
"",
from ba in hash.ComputeHash
(
Encoding.UTF8.GetBytes(observedText)
)
select ba.ToString("x2")
);
}
Solution 4
You can use Convert.ToBase64String
to convert 16 byte output of MD5 to a ~24 char string. A little bit better without reducing security. (j9JIbSY8HuT89/pwdC8jlw==
for your example)
Solution 5
Depends entirely on what you are trying to achieve. Technically, you could just take the first 12 characters from the result of the MD5 hash, but the specification of MD5 is to generate a 32 char one.
Reducing the size of the hash reduces the security, and increases the chance of collisions and the system being broken.
Perhaps if you let us know more about what you are trying to achieve we may be able to assist more.
Related videos on Youtube
Comments
-
Muhamad Jafarnejad almost 2 years
I use the following C# code to calculate a MD5 hash from a string. It works well and generates a 32-character hex string like this:
900150983cd24fb0d6963f7d28e17f72
string sSourceData; byte[] tmpSource; byte[] tmpHash; sSourceData = "MySourceData"; //Create a byte array from source data. tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData); tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource); // and then convert tmpHash to string...
Is there a way to use code like this to generate a 16-character hex string (or 12-character string)? A 32-character hex string is good but I think it'll be boring for the customer to enter the code!
-
Danger Saints almost 3 yearsMD5CryptoServiceProvider instance should be disposed
-
-
KingCronus almost 12 yearsA nice workaround, but I doubt he OP will want to have it case-sensitive and with special chars...
-
Muhamad Jafarnejad almost 12 yearsthanks for your answer. and sorry about my bad explanation. I want to publish an application for windows, the user should buy the license to use my application, so my application request two fields: USERNAME: ... , and KEY: .... I want to hash the USERNAME and create the KEY, then the user should enter the specific USERNAME and KEY. my problem here is that the KEY should be 12-characters, (But in MD5 hash, I get the 32-char KEY). please help me, i really need it.
-
yǝsʞǝla about 9 yearsThe source: msdn.microsoft.com/en-us/library/…
-
Igor Gatis about 9 yearsWhy "similar to UNIX format"? What it is not exactly the same?
-
DavidG over 8 yearsYou should always say where you get code from if you copy/paste from somewhere, otherwise it is classed as plagiarism.
-
Paolo Iommarini over 8 yearsThe class MD5 implements IDisposable, remember to dispose your instance. ;)
-
Oliver Bock about 8 yearsIn general you should hash a lossless text encoding, like UTF8.
-
Monsignor almost 7 yearsBTW checked with the
BenchmarkDotNet
that the combination ofCryptography.MD5
andBitConverter
(see @Michaels's answer) has the best performance. -
bh_earth0 about 6 yearsthis gives different result from online md5 checkers. or is it just me??
-
bh_earth0 about 6 yearsif you use UTF8, it puts bytordermark(bom). file_content and string WON'T match. to get rid of bom, i used
new utf8encoding(false);
when file.read/write -
Richard Schneider over 5 yearsIts better to
System.Text.Encoding.Utf8.GetBytes
for people outside of USA. -
Prashant Pimpale over 5 years@Anant How to decrypt the MD5?
-
Anant Dabhi over 5 years@PrashantPimpale MD5 is a digest algorithm. Think of it as converting a cow into a steak.
-
Prashant Pimpale over 5 yearsYes tried with
TripleDESCryptoServiceProvider
and done! -
Prashant Pimpale over 5 yearsjust wanted to encrypt an Email Id and then decrypt it
-
eddyP23 about 5 years@bh_earth0 it seems that
BitConverter
doesn't work in the same fashion on windows and linux, see this question: stackoverflow.com/questions/11454004/… -
Klesun almost 5 yearsWhat does the
"X2"
mean? -
Anant Dabhi almost 5 years@ArturKlesun , It formats the string as two uppercase hexadecimal characters.
-
Marc.2377 over 4 yearsOne-liner, in method syntax:
return string.Join( "", hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x => x.ToString("x2") ) );
-
Marc.2377 over 4 years... in which case, I propose
return string.Concat( hash.ComputeHash( Encoding.UTF8.GetBytes(observedText) ).Select( x => x.ToString("x2") ) );
instead. It's a little bit shorter, possibly clearer intention, and performs marginally faster (<10% perf. increase). -
jklemmack almost 4 years@PrashantPimpale MD5 is one way - it can create a hash, but information is destroyed and cannot be recovered. It's value comes from hashing two different things then comparing the hashes. Works well for things like passwords, or comparing file contents. If you want to reverse "encryption", the look at things like AES or DES (docs.microsoft.com/en-us/dotnet/api/…). They provide the ability to "encrypt" then "decrypt"
-
Detail over 3 yearsThis worked nicely for me when trying to convert an MD5 Hash (from Azure Blob properties) into a string. It produces exactly the same string as the Azure Storage container does.
-
Jawad Zeb over 3 yearsfor those who are trying to calculate for Sip or an equivalent to linux md5sum don't forget to add .ToLower()
-
Kurtis Jungersen almost 3 yearsNOTE: "Due to collision problems with MD5/SHA1, Microsoft recommends SHA256 or SHA512. Consider using the SHA256 class or the SHA512 class instead of the MD5 class. Use MD5 only for compatibility with legacy applications and data." Sources: 1) MD5 Docs linked by OP, where this notice appears, and 2) MS Docs on SHA256, with a good example
-
Rey over 2 yearsThis does not dispose the instance of MD5
-
nivs1978 over 2 yearsRemember a "using": using (var md5 = MD5.Create()) md5.ComputeHash(....);
-
Ivandro Jao over 2 yearsUsing BitConverter.ToString() also gives a nice hash-string!