ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetSHA1Hash

Calculates the SHA1 hash value of a string and returns it as a base64 string.

Source

/// <summary>
/// Calculates the SHA1 hash of the supplied string and returns a base 64 string.
/// </summary>
/// <param name="stringToHash">String that must be hashed.</param>
/// <returns>The hashed string or null if hashing failed.</returns>
/// <exception cref="ArgumentException">Occurs when stringToHash or key is null or empty.</exception>
public static string GetSHA1Hash(this string stringToHash)
{
    if (string.IsNullOrEmpty(stringToHash))
    {
        throw new ArgumentException("An empty string value cannot be hashed.");
    }

    Byte[] data = System.Text.Encoding.UTF8.GetBytes(stringToHash);
    Byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(data);
    return Convert.ToBase64String(hash);
}

Example

"Get the hash of this string".GetSHA1Hash()

Author: Steve Hiner

Submitted on: 6 jan. 2009

Language: C#

Type: System.String

Views: 6360