How to verify a hashed password in C#

1 Answer

0 votes
using System;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        string password = "SecurePassword123!@";

        string storedHash = HashPassword(password);
        Console.Write("Hash: ");
        Console.WriteLine(storedHash);
        
        string passwordToVerify = "SecurePassword123!@";

        if (VerifyPassword(passwordToVerify, storedHash)) {
            Console.WriteLine("Password is correct");
        }
        else {
            Console.WriteLine("Invalid password");
        }
    }

    // Hash a password using PBKDF2-HMAC-SHA256
    public static string HashPassword(string password) {
        byte[] salt = new byte[16];

        using (var rng = RandomNumberGenerator.Create()) {
            rng.GetBytes(salt);
        }

        var pbkdf2 = new Rfc2898DeriveBytes(
            password,
            salt,
            100000,
            HashAlgorithmName.SHA256
        );

        byte[] hash = pbkdf2.GetBytes(32);

        return Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
    }
    
    // Verify a password
    public static bool VerifyPassword(string password, string stored) {
        var parts = stored.Split(':');
        byte[] salt = Convert.FromBase64String(parts[0]);
        byte[] storedHash = Convert.FromBase64String(parts[1]);

        var pbkdf2 = new Rfc2898DeriveBytes(
            password,
            salt,
            100000,
            HashAlgorithmName.SHA256
        );

        byte[] newHash = pbkdf2.GetBytes(32);

        return CryptographicOperations.FixedTimeEquals(storedHash, newHash);
    }
}



/*
run:

Hash: 11WNF8ANmifxK3YAleBiNg==:V+RGL3MW4JYew0pyBfEafTtjEN++ZHJR0CAFPyPQn00=
Password is correct

*/

 



answered 15 hours ago by avibootz
...