Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Source for blogpost
using System;
using System.Security.Cryptography;
using System.Text;
namespace PasswordEncryptor
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Bitte Passwort eingeben:");
string password = Console.ReadLine();
string salt = Program.GetSalt();
string hashedPassword = Program.EncryptPassword(password) + salt;
Console.WriteLine($"Dein Passwort-Hash ist {hashedPassword}");
// ==============================================
string databaseSalt = salt;
string databaseHash = hashedPassword;
Console.WriteLine("Bitte zu prüfendes Passwort eingeben");
string passwordToVerify = Console.ReadLine();
bool correct = Program.IsPasswordCorrect(passwordToVerify, databaseSalt, databaseHash);
if (correct)
{
Console.WriteLine("Passwörter sind identisch!");
}
else
{
Console.WriteLine("Falsches Passwort eingegeben!");
}
}
private static string EncryptPassword(string password)
{
using(var sha256 = SHA256.Create()) {
var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
var hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
return hash;
}
}
private static string GetSalt()
{
byte[] bytes = new byte[16];
using(var keyGenerator = RandomNumberGenerator.Create())
{
keyGenerator.GetBytes(bytes);
return BitConverter.ToString(bytes).Replace("-", "").ToLower();
}
}
private static bool IsPasswordCorrect(string password, string salt, string hash)
{
string correctPassHash = hash.Replace(salt, "");
string newPassHash = Program.EncryptPassword(password);
if (correctPassHash.Equals(newPassHash))
{
return true;
}
else
{
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment