DEV Community

Cover image for Hashing Password combining with Salt in C# and VB.NET

Hashing Password combining with Salt in C# and VB.NET

1001binary profile image 1001binary ・2 min read

In this post, I show you how to protect password using hash-salt mechanism.

Hashing password using salt is one of the best practices in protecting user accounts from hackers and who you don't want anyone to see plain-text passwords in databases or text files. This is really great. In case hackers have stolen databases, they also need more time to decryte them. It won't be easy at all. At the same time, you have time to reset all passwords or suggest users to change passwords right away.

My background is .NET developer. That's why I have written two simple functions in C# and VB.NET as below.


public class SecurityHelper
    public static string GenerateSalt(int nSalt)
        var saltBytes = new byte[nSalt];

        using (var provider = new RNGCryptoServiceProvider())

        return Convert.ToBase64String(saltBytes);

    public static string HashPassword(string password, string salt, int nIterations, int nHash)
        var saltBytes = Convert.FromBase64String(salt);

        using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, saltBytes, nIterations))
            return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(nHash));
Enter fullscreen mode Exit fullscreen mode


Public Class SecurityHelper
    Public Shared Function GenerateSalt(ByVal nSalt As Integer) As String
        Dim saltBytes = New Byte(nSalt) {}

        Using provider = New RNGCryptoServiceProvider()
        End Using

        Return Convert.ToBase64String(saltBytes)
    End Function

    Public Shared Function HashPassword(ByVal password As String, ByVal salt As String, ByVal nIterations As Integer, ByVal nHash As Integer) As String
        Dim saltBytes = Convert.FromBase64String(salt)

        Using rfc2898DeriveBytes = New Rfc2898DeriveBytes(password, saltBytes, nIterations)
            Return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(nHash))
        End Using
    End Function
End Class
Enter fullscreen mode Exit fullscreen mode

For example:

string pwd = "123Abc#@";
string salt = SecurityHelper.GenerateSalt(70);
string pwdHashed = SecurityHelper.HashPassword(pwd, salt, 10101, 70);
Enter fullscreen mode Exit fullscreen mode

Hope you enjoy this post.

Happy coding :)

Discussion (1)

parajdox profile image
John Dave Dalmao

how do we decrypt this?

Forem Open with the Forem app