Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I hash passwords with salt and iterations using PBKDF2 HMAC SHA-256 or SHA-512 in C#?

I would like to find a solution or method that will allow me to add salt and control the number of iterations. The native Rfc2898DeriveBytes is based on HMACSHA1. Ideally, using SHA-256 or SHA-512 will make the system future proof.

This is the best example I have found so far: http://jmedved.com/2012/04/pbkdf2-with-sha-256-and-others/ but when I ran it with SHA-256 it was actually slower than with SHA-512. I used 64k iterations, a guid for salt and different same length passwords to compare.

I also found this solution: http://sourceforge.net/projects/pwdtknet/ which has full source code available. It seems to be more robust.

So far I am not able to get the same output from each of them.

like image 687
jpshook Avatar asked May 02 '13 15:05

jpshook


People also ask

What is PBKDF2 HMAC SHA256?

The PBKDF2-HMAC-SHA256 Password Storage Scheme provides a mechanism for encoding user passwords using the PBKDF2-HMAC-SHA256 message digest algorithm. This scheme contains an implementation for the user password syntax, with a storage scheme name of "PBKDF2-HMAC-SHA256".

What is PBKDF2 iteration?

PBKDF2. PBKDF2 is a simple cryptographic key derivation function, which is resistant to dictionary attacks and rainbow table attacks. It is based on iteratively deriving HMAC many times with some padding. The PBKDF2 algorithm is described in the Internet standard RFC 2898 (PKCS #5).

Is PBKDF2 HMAC SHA1 secure?

Sure. SHA-256, or larger, might be more efficient if you want to generate more key material. But PBKDF2-HMAC-SHA1 is fine. Also standard HMAC use has not been compromised, but again, longer hashes are in principle more secure in that scenario.

Is Sha 512 still secure?

The SHA1, SHA256, and SHA512 functions are no longer considered secure, either, and PBKDF2 is considered acceptable. The most secure current hash functions are BCRYPT, SCRYPT, and Argon2. In addition to the hash function, the scheme should always use a salt.


2 Answers

The more recent alternative is Microsoft.AspNetCore.Cryptography.KeyDerivation NuGet package, which allows to use PBKDF2 with SHA-256 and SHA-512 hash functions, which are stronger than SHA-1 which is built into Rfc2898DeriveBytes. The advantage over third-party libraries mentioned in other answers is that it's implemented by Microsoft, so you don't need to perform a security audit for it, once you already rely on .NET platform. Documentation is available at docs.microsoft.com.

like image 109
ovolko Avatar answered Sep 27 '22 18:09

ovolko


My CryptSharp library can do PBKDF2 with any arbitrary HMAC. Salt and iterations can be controlled. Look in the CryptSharp.Utility namespace. It's there along with a C# Scrypt implementation and a couple other things.

like image 40
James Avatar answered Sep 27 '22 18:09

James