create a password in csharp

Here's an example of creating a hashed password in C# using the SHA256 algorithm:

main.cs
using System;
using System.Security.Cryptography;
using System.Text;

public static string HashPassword(string password)
{
    byte[] salt = new byte[16];
    using (var rng = RandomNumberGenerator.Create())
    {
        rng.GetBytes(salt);
    }

    byte[] hashedPassword = HashPasswordWithSalt(Encoding.UTF8.GetBytes(password), salt, 10000, 32);

    return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hashedPassword)}";
}

private static byte[] HashPasswordWithSalt(byte[] password, byte[] salt, int iterations, int hashLength)
{
    using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA256))
    {
        return pbkdf2.GetBytes(hashLength);
    }
}
708 chars
25 lines

To use this method, simply call HashPassword("plaintextpassword") and it will return a string in the format of "base64salt:base64hashedpassword". To verify a password, you would need to store the salt used for that password and then hash the entered password with that salt and compare the result with the stored hashed password.

gistlibby LogSnag