Apr 162012

.NET has built-in class handling all your PBKDF2 needs. It is called Rfc2898DeriveBytes and it works as long as you stick to SHA-1 HMAC. If your needs move in direction of SHA-256, you are out of luck.

Therefore I created Pbkdf2 class that takes any HMAC algorithm (e.g. SHA-1, SHA-256 or SHA-512) as input and allows you to derive key based on it.

using (var hmac = new HMACSHA256()) {
    var df = new Pbkdf2(hmac, password, salt, iterations);

Full code is available for download.

  7 Responses to “PBKDF2 with SHA-256 (and others)”

Comments (6) Pingbacks (1)
  1. Hello Josip,
    I have just tried your code, really great stuff. I am looking to use this in a commercial app, would this be available under an MIT or Microsoft Public licence?
    Many Thanks,

    • Hi,
      Full licence is available for viewing at http://www.jmedved.com/license/.
      It is MIT and thus you are free to use code in any manner.
      I always reserve a right to a beer if we ever meet. :)

      • Hi, Josip

        To use pbkdf2 along with sha512 algorithm should I just substitute “hmac = new HMACSHA256() ” for “hmac = new HMACSHA512()” ? Or this code only works for pbkdf2 + sha256?

        Also, I didn’t understand in which part of your code shows the implementation/call of the pbkdf2 algorithm.

        Thank you.

        • Hi,

          you are correct about substitution.
          No code written here shows pbkdf2 in action since it is just an excerpt. In order to see full code, just download source (link is at end of text).

  2. Hi, Josip

    Thank you for your quick answer. If you don’t mind I have another question. If I use the SHA256 algorithm then I would have a hash of 32 bytes, but is it correct to receive 64 bytes even if I use 64 as a parameter of the hash.getBytes(64) function? I don’t understand why. O thought SHA256 should always return 32 bytes. What’s the explanation?

    Thank you in advance.


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>