Monday, 8 March 2010

C# ASP.NET: Password Hasher Library

Here is a library i've created which allows you to hash a password in C#.NET... im sure the vb is similar too.
This si a one-way hash, which means you can only encrypt and not decrypt. This is a standard way of practise and necessary for a good secure ASP.NET application.

// <copyright file="PasswordHash.cs" company="Banty">
// Copyright (c) 2010 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email></email>
// <date>08-03-2010</date>
// <summary>Enables a user to hash a password against a salt.</summary>

namespace Banty
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

/// <summary>
/// Enables a user to hash a password against a given 'salt'.
/// </summary>
public class PasswordHash
/// <summary>
/// Creates a random salt. This can be used if the password
/// isn't being hashed against anything specific.
/// </summary>
/// <param name="size">Size of the salt.</param>
/// <returns>A string represeting the salt.</returns>
public static string CreateSalt(int size)
// Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];

// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);

/// <summary>
/// Create a password hash. This will hash a given password
/// against the given salt to provide a one-way hash of the password.
/// </summary>
/// <param name="password">Specified password to be hashed.</param>
/// <param name="salt">The salt to hash against.</param>
/// <returns>An encrypted representation of the password.</returns>
public static string CreatePasswordHash(string password, string salt)
string hashedPwd = string.Empty;

string saltAndPwd = String.Concat(password, salt);
hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");
catch (Exception ex)
throw new Exception(string.Format("ERROR: in [{0}]. Could not hash specified password.", MethodBase.GetCurrentMethod().Name), ex);

return hashedPwd;

No comments: