Easy SHA1 encryption in C# / ASP.NET

The .NET framework has a some useful hidden methods available. One of them is a static method of the FormAuthentication class, from the System.Web.Security namespace, HashPasswordForStoringInConfigFile().

using System;
using System.Web;
using System.Web.Security;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string password = FormsAuthentication.HashPasswordForStoringInConfigFile("password", "SHA1");
        Response.Write(password);
    }
}

This code writes “5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8” to the page.

Advertisements

9 Responses to “Easy SHA1 encryption in C# / ASP.NET”

  1. Aaron Says:

    Good Solution, it help me out!

  2. Max Says:

    What about raw_output parameter? Like in PHP 5!

    • saezndaree Says:

      The method described in the article is a shortcut. If you want more control over the output etc., I suggest that you look at the System.Security.Cryptography namespace, and at the MD5 and MD5CryptoServiceProvider classes.

      As an example:

      using System.Security.Cryptography;

      MD5 md5 = MD5CryptoServiceProvider.Create();

      string txt = “Hello world”;

      byte[] buffer = System.Text.Encoding.UTF8.GetBytes(txt);

      byte[] hash = md5.ComputeHash(buffer, 0, buffer.Length);

      foreach (byte b in hash)
      {
      Console.Write(b + “;”);
      }

  3. Jack Says:

    The result of the first method is different of the result of the second method.
    It’s correct ?

    • saezndaree Says:

      The main example uses SHA1, while my second piece of code uses the MD5 algorithm. My second example also writes the raw byte values to the output stream, while the main example returns a concatenated hexadecimal representation.

      System.Security cryptography has an SHA1 counterpart to the MD5 class, and I believe HashPasswordForStoringInConfigFile accepts “md5” as it second argument. Ultimately, both methods can do the same thing.

  4. cfillion Says:

    @Jack Yes, it’s strange… 😮

  5. jonijo Says:

    brilliant…simple and extremely helpfull…

  6. mkhalifap Says:

    I have a ASP.NET application, i used ‘sha1’ hashing for password,

    FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, “SHA1”);

    i develop same application in C# windows application, but i can’t login.
    both application has only one database. how can I get this

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s


%d bloggers like this: