Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

Encoding a string with MD5 in C#

It is a common sense to keep user passwords encoded so they won't be compromised in case of hacker attack. Here is simple function doing this:

 /// <summary>
 /// Encodes a string using MD5. Don't forget to add ref. to System.Security.Cryptography
 /// </summary>
 /// <param name="password">A string to encode</param>
 /// <returns>Encoded string in Hex format</returns>
 public static string EncodeString(string password)
 {
     string md5encoded;
 
     // MD5 is disposable:
     using (MD5 md5 = new MD5CryptoServiceProvider())
         md5encoded = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(password)));
 
     // Removing dashes to shrink result length:
     return md5encoded.Replace("-", String.Empty);
 }
 

This function will return you string similar to this: E10ADC3949BA59ABBE56E057F20F883E.

Doesn't look like common MD5 string, should be like this: 4QrcOUm6Wau+VuBX8g+IPg== isn't it? To convert our result to such view we need just Bas64 it. Use this line instead of on example above:

 md5encoded = Convert.ToBase64String(md5.ComputeHash(Encoding.ASCII.GetBytes(password)));

So the whole function becoming to this:

 public static string EncodeString(string password)
 {
     string md5encoded;
 
     // MD5 is disposable:
     using (MD5 md5 = new MD5CryptoServiceProvider())
         md5encoded = Convert.ToBase64String(md5.ComputeHash(Encoding.ASCII.GetBytes(password)));
 
     // Removing dashes to shrink result length:
     return md5encoded;
 }
 

 

Is Power of 2? (C#)

Continue playing with Integers. Here is how to determine if a number is power of 2 or not:

 /// <summary>
 /// Checks if an integer is power of 2
 /// </summary>
 /// <param name="i">An int number to check</param>
 /// <returns>true if i is power of 2, false if otherwise</returns>
 public static bool IsPower2(int i)
 {
     return (i != 0) && ((i & -i) == i);
 }