using System.Security.Cryptography;
using System.Collections.Generic;
public static void Main()
var encodedPassword = SecurityHelper.EncodePassword("password", "{MD5}27hLPwlepgtEBGDuh9hxp1BA4X0w", MembershipPasswordFormat.Hashed);
Console.WriteLine(encodedPassword);
public static class SecurityHelper
internal static string EncodePassword(
string passwordHashFromDb,
MembershipPasswordFormat passwordFormat)
string digestLabel = SecurityHelper.GetDigestLabel(passwordHashFromDb);
if (passwordFormat == MembershipPasswordFormat.Clear || string.IsNullOrEmpty(digestLabel))
if (passwordFormat != MembershipPasswordFormat.Hashed)
throw new Exception("UnsuportedPasswordFormat");
byte[] salt = SecurityHelper.GetSalt(SecurityHelper.GetPassword(passwordHashFromDb), digestLabel);
return SecurityHelper.Crypt(enteredPassword, salt, digestLabel);
internal static string GetDigestLabel(string passwordHash)
int num1 = passwordHash.IndexOf('{');
int num2 = passwordHash.IndexOf('}');
return num1 != -1 || num2 != -1 ? passwordHash.Substring(num1 + 1, num2 - 1) : (string) null;
internal static string Crypt(string plaintext, byte[] saltBytes, string algorithm)
HashAlgorithm hashAlgorithm = SecurityHelper.GetHashAlgorithm(algorithm);
byte[] bytes = Encoding.UTF8.GetBytes(plaintext);
byte[] buffer = new byte[bytes.Length + saltBytes.Length];
for (int index = 0; index < bytes.Length; ++index)
buffer[index] = bytes[index];
for (int index = 0; index < saltBytes.Length; ++index)
buffer[bytes.Length + index] = saltBytes[index];
byte[] hash = hashAlgorithm.ComputeHash(buffer);
byte[] inArray = new byte[hash.Length + saltBytes.Length];
for (int index = 0; index < hash.Length; ++index)
inArray[index] = hash[index];
for (int index = 0; index < saltBytes.Length; ++index)
inArray[hash.Length + index] = saltBytes[index];
string base64String = Convert.ToBase64String(inArray);
return "{" + algorithm + "}" + base64String;
internal static byte[] GetSalt(string passwordHash, string algorithm)
HashAlgorithm hashAlgorithm = SecurityHelper.GetHashAlgorithm(algorithm);
byte[] numArray = Convert.FromBase64String(passwordHash);
int num = hashAlgorithm.HashSize / 8;
if (numArray.Length <= num)
byte[] salt = new byte[numArray.Length - num];
for (int index = 0; index < salt.Length; ++index)
salt[index] = numArray[num + index];
private static HashAlgorithm GetHashAlgorithm(string algorithmLabel)
return HashAlgorithm.Create("MD5");
throw new CryptographicException("HashAlgorithm not found!");
internal static string GetPassword(string passwordHash)
int num = passwordHash.IndexOf('}');
return num != -1 ? passwordHash.Substring(num + 1) : passwordHash;
public enum MembershipPasswordFormat