Monday, July 18, 2011

Encrypt and Decrypt extention

Today we offer Encrypt/Decrypt extension by MD5 algorithm:
/// <summary>
/// Encrypt input by MD5
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string Encrypt(this string input)
{
    using (MD5 md5Hash = MD5.Create())
    {
        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder stringBuilder = new StringBuilder();

        // Loop through each byte of the hashed data
        // and format each one as a hexadecimal string.
        Array.ForEach(data,
             item => stringBuilder.Append(item.ToString("x2"))
            );
        // Return the hexadecimal string.
        return stringBuilder.ToString();
    }
}

/// <summary>
/// Verify a hash against a string.
/// </summary>
/// <param name="input"></param>
/// <param name="hash"></param>
/// <returns></returns>
public static bool Decrypt(this string hash, string input )
{
    // Hash the input.
    string hashOfInput = Encrypt(input);
    // Create a StringComparer an compare the hashes.
    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
    return (comparer.Compare(hashOfInput, hash) == default(int)) ? true : false;
}

Example:
public class Foo
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

//Your code
Foo foo = new Foo
{
    UserName = "admin",
    //Encrypt
    Password = "12345".Encrypt()
};

//Decrypt
bool isValid = foo.Password.Decrypt("12345");


No comments:

Post a Comment