新文章

2012年12月23日 星期日

[C#]MD5 encryption with Salted Hash

Here is the MD5 encryption function in C# and application within salted hash.
We can use namespace,System.Security.Cryptography in C# to encrypt string easily.
Here is the code below :


/// <summary>
/// 取得 MD5 編碼後的 Hex 字串
/// 加密後為 32 Bytes Hex String (16 Byte)
/// </summary>
/// <span  name="original" class="mceItemParam"></span>原始字串</param>
/// <returns></returns>
public static string GetMD5(string original)
{
     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     byte[] b = md5.ComputeHash(Encoding.UTF8.GetBytes(original));
     return BitConverter.ToString(b).Replace("-", string.Empty);
}

It's convert the string to 32 Bytes Hex String.
In other hands,we can increase the complexity by using salted hash.
In addition,the converted value will become longer associated to the lengths of salt value and original string.


        public static string GetSaltedMD5(string original, string saltedVal)
        {
            if (saltedVal.Length == 0)
            {
                saltedVal = "SaltedValueTest";
            }
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] b = Encoding.UTF8.GetBytes(original);
            byte[] SaltValue = Encoding.Default.GetBytes(saltedVal);
            byte[] ToSalt = new byte[b.Length + SaltValue.Length];
            b.CopyTo(ToSalt, 0);
            SaltValue.CopyTo(ToSalt, b.Length);
            byte[] SaltPWD = md5.ComputeHash(ToSalt);
            byte[] PWD = new byte[SaltPWD.Length + SaltValue.Length];
            SaltPWD.CopyTo(PWD, 0);
            SaltValue.CopyTo(PWD, SaltPWD.Length);
            return Convert.ToBase64String(PWD);
        }







沒有留言:

張貼留言