Utility class for encrypting passwords and comparing two encrypted passwords. : Password « Security « C# / C Sharp






Utility class for encrypting passwords and comparing two encrypted passwords.

  

/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

/// <summary>
/// Utility class for encrypting passwords and comparing two encrypted passwords.
/// </summary>
public static class PasswordUtil
{
    /// <summary>
    /// Creates a hash for the given password string using SHA512 algorithm.
    /// </summary>
    /// <param name="password">The password string to hash.</param>
    /// <returns>The hash value.</returns>
    public static byte[] CreatePasswordHash(string password)
    {
        if (string.IsNullOrEmpty(password))
            return null;
        SHA1Managed hasher = new SHA1Managed();
        byte[] hashed = hasher.ComputeHash(Encoding.ASCII.GetBytes(password));
        hasher.Clear();
        return hashed;
    }

    /// <summary>
    /// Compares two hashes, returns true if they are equal.
    /// </summary>
    /// <param name="pw1">First hash.</param>
    /// <param name="pw2">Second hash.</param>
    /// <returns>true if the hashes are equal.</returns>
    public static bool AreEqual(byte[] pw1, byte[] pw2)
    {
        if (pw1.Length != pw2.Length)
            return false;
        for (int i = 0; i < pw1.Length; i++)
        {
            if (pw1[i] != pw2[i])
                return false;
        }
        return true;
    }
}

   
    
  








Related examples in the same category

1.Directory Services Change PasswordDirectory Services Change Password
2.Password Encrypter
3.Send Password Email
4.Get Random Password Using GUID