Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to hash and salt passwords c#
Bunnytoes (111)

Hashing and salting passwords

I decided to make this tutorial because I am using this for a big project and so you don't have to search online forever, to start add these two using tags to the top

using System.Text;
using System.Security.Cryptography;

ok, now add this at the top before the main method

public static string ComputeHash(byte[] bytesToHash, byte[] salt)
// pass in two arguments
{
    var byteResult = new Rfc2898DeriveBytes(bytesToHash, salt, 10000);
    return Convert.ToBase64String(byteResult.GetBytes(24));
}

ok, this will be the part that computes your hash, now to generate the salt you do this

public static string GenerateSalt()
{
    var bytes = new byte[160 / 8];
    var rng = new RNGCryptoServiceProvider();
// very good for security
    rng.GetBytes(bytes);
    return Convert.ToBase64String(bytes);
}

alright, this is almost all we have to do, now we put the generation code in the main method

Console.WriteLine("What you want to hash and salt");
    string toHash = Console.ReadLine();
//store what to hash

//hashing and salting
var newSalt = GenerateSalt();
//generate salt
var hashedPassword = ComputeHash(Encoding.UTF8.GetBytes(toHash), Encoding.UTF8.GetBytes(newSalt));
//hash and salt the rest of it

Console.WriteLine($"Your hashed password is {hashedPassword}");
      Console.WriteLine($"Your salt is {newSalt}");
//write out the hashed and salted password and the normal salt

that is it for the tutorial and this is one of many ways to hash passwords but this was the easiest I could find online :D
I hope you enjoy and hope this was helpful!

Comments
hotnewtop
Bunnytoes (111)

@Cuber1515 this may help you understand better

cuber1515 (55)

@Bunnytoes also on the spotlight page for your scrambler I forked I can't respond because for some reason I'm in education mode, but I didn't put that since I forked from you so that's whatever you put. Actually could tell sushri that it's a fork since I can't tell him.