JP Hellemons Building E-commerce web applications

Easy generate SHA1 in Asp.Net

1. August 2012 17:15by jphellemons in C#

This is the easiest way to encrypt a string to sha-1 in Asp.Net C#:

string sha1 = FormsAuthentication.HashPasswordForStoringInConfigFile(toGenerate, "sha1");

Do not forget this reference at the using  by the way:

using System.Web.Security;

Visual Studio tells you that it's deprecated as you can see on MSDN.

It has been deprecated because of all the .net 2.0 membership providers and ‘new’ features. So the recommended way to get an SHA1 hash is:

/// <summary>
/// Calculates SHA1 hash
/// </summary>
/// <param name="text">input string</param>
/// <param name="enc">Character encoding</param>
/// <returns>SHA1 hash</returns>
private static string CalculateSha1(string text, Encoding enc)
{
byte[] buffer = enc.GetBytes(text);
SHA1CryptoServiceProvider cryptoTransformSha1 =
new SHA1CryptoServiceProvider();
string hash = BitConverter.ToString(
cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "");
return hash;
}

Do not forget this reference at the using :

using System.Security.Cryptography;

Use it like this:

string sha1 = CalculateSha1(toGenerate, Encoding.Default);

 

Good luck coding!

Of course you can flattr me.

Shout it kick it on DotNetKicks.com

Share or Bookmark this post…
  • del.icio.us
  • Digg
  • DotNetKicks
  • eKudos
  • E-Mail
  • Facebook
  • Google
  • LinkedIn
  • msdn Social
  • Reddit
  • NuJIJ
  • Slashdot
  • TwitThis
  • StumbleUpon

Pingbacks and trackbacks (1)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading