pbkdf2_sha256 C# implementation

1.1k views Asked by At

I've got a database where passwords are stored as pbkdf2_sha256. I want to create a tool (in C#) which should create new passwords.

My problem is: How can I encrypt the password in C#? I found a Java-Class which works for me, but I can not use this sample in C#. Is there a smilar way?

I tried also other classes but they do not seem to work.

EDIT: I found this class for C#. But when I call the ValidatePassword-Method it returns false. (Password and Hash are correct).

EDIT2: I found also this C# class but it doesn't seem to work. What did I wrong?

Here is the code which I use:

var salt = "FbSnXHPo12gb";
var password = "geheim";
var interactions = 12000;


using (var hmac = new HMACSHA256())
{
    var df = new Pbkdf2(hmac, password, salt, interactions);
    Console.WriteLine(BitConverter.ToString(df.GetBytes(32)));
    Console.WriteLine(String.ByteArrayToString(df.GetBytes(32)));
    Console.WriteLine(UTF8Encoding.UTF8.GetString(df.GetBytes(32)));
    Console.WriteLine(Convert.ToBase64String(df.GetBytes(32)));
}

//hash I should get: 
//pbkdf2_sha256$12000$FbSnXHPo12gb$LEpQrzPJXMI0m3tQuIE5mknqCv1GWgT5X2rWyLHN0Xk=

//hash I get:
//Rc8oMeSrbWyIJ+aXvGegFowKcIlwk8eIRyxXUf/a+t0=
2

There are 2 answers

0
Josip Medved On BEST ANSWER

Do not convert hexadecimal output to base-64 string but convert bytes to it directly. And also notice that you will get new bytes on each df.GetBytes call. Equivalent example would be:

var salt = "FbSnXHPo12gb";
var password = "geheim";
var interactions = 12000;


using (var hmac = new HMACSHA256())
{
    var df = new Pbkdf2(hmac, password, salt, interactions);
    Console.WriteLine(Convert.ToBase64String(df.GetBytes(32)));
}

//hash I should get: 
//pbkdf2_sha256$12000$FbSnXHPo12gb$LEpQrzPJXMI0m3tQuIE5mknqCv1GWgT5X2rWyLHN0Xk=

//hash I get:
//LEpQrzPJXMI0m3tQuIE5mknqCv1GWgT5X2rWyLHN0Xk=

Notice that Java class has a header ("pbkdf2_sha256$12000$FbSnXHPo12gb$") while C# class only returns hash.

0
Anti-weakpasswords On

I have a fork of Jither's PBKDF2 C# DeriveBytes code at my Github repository, including a PBKDF2-HMAC-SHA-256 variant, a large set of test vectors, and an interface that both generates hashes and can check the results, if that example helps you.