Any opinions expressed here are my own and not necessarily those of my employer (I'm self-employed).

May 15, 2012

Towards more secure password hashing in ASP.NET

A couple of weeks ago I was remotely involved in a discussion on password hashing in .NET with @thorsheim, @skradel, and @troyhunt. (Follow them if you're on Twitter). The background for the discussion was that password hashing using MD5/SHA-1/SHA-256 isn't quite the state of the art anymore. All the recent password breaches have triggered recommendations to make password cracking harder. The algorithms that are usually recommended are PBKDF2 (Password based key derivation function), bcrypt, or scrypt. So which of these should you choose if you're working with .NET?

I'm a conservative guy. Cryptographic algorithms are very hard to get right, as there's all sorts of things that can go wrong when you implement them. Consequently, I prefer to use whatever is available in the .NET framework. That's because Microsoft have crypto-experts on staff, and they've also pioneered the SDL which means you should expect high quality implementations of their (security critical) software. So it's really a trust thing. At the time of writing, PBKDF2 is the only algorithm of the three mentioned that's readily available in the framework. You probably see where this is leading: bcrypt and scrypt are disqualified in my book. When it comes to cryptographic functions, stick with the framework! PBKDF2 is the best alternative for now.

Following the discussion on Twitter, @skradel shared a library where he had wrapped the built-in PBKDF2 as a HashAlgorithm. That way, PBKDF2 (through his wrapper) could easily be used by other parts of the framework, such as the SqlMembershipProvider. It really was an elegant solution. He blogged about it in: Strong Password Hashing for ASP.NET, you should check it out (@thorsheim was so delighted that he had to blog about it too :).

When you're dealing with PBKDF2, you'll see that it takes a couple of parameters. @skradel's already chosen some reasonable defaults in his implementation so it's all hidden and taken care of there. But if you were to implement this yourself and explain to someone how you chose those parameters, what then?

I couldn't find much guidance on the Internet so I started digging into the PBKDF2 standard to find out more.

PBKDF2 parameters
The PBKDF2 is backed by H-MAC-SHA-1 which is a keyed hash function (see HMAC). The supplied password is used as the key, while the salt is used as the input text, concatenated with a block identifier. The whole idea behind PBKDF2 is to introduce a drastic increase in the workload for a password cracker. In the default setup, H-MAC-SHA-1 is run a 1 000 times to generate the output for a password. This is a negligible workload when you're checking that a user entered the correct password. However, for an attacker running an offline attack with a password cracker that needs to try millions of passwords the extra workload really adds up and slows down the attack significantly.

Next, there are a couple of things to take into consideration when implementing PBKDF2 password.
  • It requires a salt that's at least 64 bit (8 bytes)
  • You can select a number of iterations (1 000 is the default)
  • You must choose how many bytes to output
  • You need to be sure you encode your passwords correctly (remember how not to hash?)
So, how long should the salt be? I have found almost no guidance on the length of the salt, except for a note on the Rainbow table article on Wikipedia. Considering that the salt's only job is to introduce uniqueness to the calculation and that it's not a secret, I cannot see why a 64-bit salt should not get the job done. Do note that the SqlMembershipProvider uses 128-bit salts, and that's also what's used in bcrypt. So you might just do like the big boys do and go with a 128-bit salt. What's more important is how you generate a salt. You should use a cryptographic RNG for that. I've included an example at the very end of the code samples that does exactly that.

You'll also need to decide on how many iterations to use for the calculation — and now we're getting to the core of the issue. The number of iterations dictate the workload, which is the whole point of using PBKDF2 to begin with. So the recommended setting is: "as high as possible." To maximize this you'll have to test how many iterations you can run before it would become a noticeable delay for the user and hence start to effect the user experience negatively. This of course depends on the hardware you're running so you'll probably need to do some benchmarking here.

Then there's how many bytes to output. The standard gives us some useful hints here:
Thus, even if a long derived key consisting of several pseudorandom function outputs is produced from a key, the effective search space for the derived key will be at most 160 bits. Although the specific limitation for other key sizes depends on details of the HMAC construction, one should assume, to be conservative, that the effective search space is limited to 160 bits for other key sizes as well.
There it is. You'd want the largest effective key space, nothing more, nothing less. That means that you should generate 160-bit (20 bytes) of output. Remember that the security is still bound by the randomness of the passwords used. Password entropy is often used as a term to describe the complexity involved in guessing a password. Have a look at that last link, and you'll see that to have the "guessability" of the passwords match the limits to PBKDF2's output (i.e. 160-bit password entropy), users would have to choose truly random passwords that where 27 characters long, assuming you accepted alphanumeric case sensitive passwords (a-z,A-Z,0-9). As you probably know, users tend to select passwords that are not very random and that are much shorter. So rest assured that it's the passwords that will be killing you here, not the security of PBKDF2.

Rounding of, I have to remind you to use a proper character encoding when translating the passwords to bytes that can be input to the PBKDF2 function (see the sample code). If you feel like giving the passwords' ASCII bytes to PBKDF2, go read How not to hash passwords in .NET instead. That's really important.

And remember also, PBKDF2 is NOT a silver bullet. The RFC puts it quite well:
Password-based cryptography is generally limited in the security that it can provide, particularly for methods [...] where off-line password search is possible. While the use of salt and iteration count can increase the complexity of attack [...], it is essential that passwords are selected well, and relevant guidelines [...] should be taken into account. It is also important that passwords be protected well if stored.
So there. That was my advice on how to set up PBKDF2 when used to hash passwords. If you have anything to add to this please leave a comment. I'd appreciate that.

Appendix: A demonstrational PBKDF2 implementation.
To figure out how PBKDF2 actually works, I implemented it. Here's the source code, which maps rather directly to the steps outlined in the RFC. I wrote it for demonstrational purposes, so it's not optimized or anything. So I hope it's understandable.

Disclaimer: DON'T use this PBKDF2 implementation for anything other than demo purposes. As I demonstrated earlier in this post, PBKDF2 is available in the .NET framework, you should use that instead.

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

namespace PBKDF2Example
    class PBKDF2_demo

        static void Main(string[] args)
            var enc = Encoding.GetEncoding(Encoding.UTF8.CodePage,
                new EncoderExceptionFallback(),
                new DecoderExceptionFallback());
            var password = enc.GetBytes("passwordPASSWORDpassword");
            var salt = enc.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt");
            var iterations = 4096;
            var keylength = 25;

            var result = PBKDF2(password, salt, iterations, keylength);


        static byte[] PBKDF2(byte[] password,
            byte[] salt,
            int iterations,
            int derivedKeyLength)

            var hashLength = 0;

            using (var hmac = new HMACSHA1())
                hashLength = hmac.HashSize / 8;

            //Our number of blocks
            var length = (int)Math.Ceiling(
                ((decimal)derivedKeyLength) / ((decimal)hashLength));

            var derivedKey = new byte[derivedKeyLength];
            using (var ms = new MemoryStream())
                for (int blockIndex = 1; blockIndex <= length; blockIndex++)
                    var block = CalculateBlock(password, salt,
                        iterations, blockIndex);
                    ms.Write(block, 0, block.Length);
                return ms.ToArray();


        static byte[] CalculateBlock(byte[] password,
            byte[] salt,
            int iterations,
            int blockIndex)
            var blockBytes = BitConverter.GetBytes(blockIndex);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(blockBytes, 0, blockBytes.Length);

            byte[] u1;
            using (var hmac = new HMACSHA1(password))
                var firstInput = new byte[salt.Length + blockBytes.Length];
                Array.Copy(salt, firstInput, salt.Length);
                Array.Copy(blockBytes, 0, firstInput,
                    salt.Length, blockBytes.Length);
                u1 = hmac.ComputeHash(firstInput);

            byte[] lastvalue = u1;
            byte[] newvalue;
            byte[] result = u1;
            for (int i = 1; i < iterations; i++)
                using (var hmac = new HMACSHA1(password))
                    newvalue = hmac.ComputeHash(lastvalue);
                    for (int j = 0; j < newvalue.Length; j++)
                        result[j] = (byte)(newvalue[j] ^ result[j]);
                    lastvalue = newvalue;
            return result;

        //Returns 128-bit salt
        static byte[] GetNewSalt()
            var salt = new byte[16];
            using (var rng = RNGCryptoServiceProvider.Create())
                return salt;




  1. 64-bits is fine for a salt value. The point of salts/uniqueness is to prevent an attacker from being able to simultaneously attack several hashes with the same salt. With random 64-bit salt values, there would have to about 5 billion hashes (slightly more than 2^32) on average before two would have the same salt value.

  2. Great article. I just used something similar recently.

  3. Nice, if you would prefer to use HMACSHA256 or HMACSHA512 instead of the HMACSHA1 in the ageing PBKDF2 standard then I recommend taking a look at this open source API:


  4. I must say, I'm impressed that you still managed to come up with a pretty workable way to incorporate a password out of the PBKDF2 standard; that would be helpful for programmers who still haven't worked out using the newer systems.

  5. Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    2. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
      Cyber Security Projects for Final Year

      JavaScript Training in Chennai

      Project Centers in Chennai

      JavaScript Training in Chennai

  6. View this page to know how to track cell phone without installing spying application.

  7. Obat Aborsi,, Obat Penggugur Kandungan,,
    Nice bag you can earn money from that
    Thanks for your posting
    Visit me @, Jual Obat Aborsi,,

  8. By taking the time to read a lot of information like this to add my insight . cara menggugurkan hamil

  9. here you can get the free premium apps in free thorugh Lucky Patcher android worldfree4u hollywood

  10. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    website design company in patna
    website development company in patna
    website development in patna

    web design company in patna
    web development company in patna
    website design in patna

    website design patna
    seo company in patna
    seo company in bihar

  11. Web Ocean Design is the best IT services provider for complete mobile and web application development. The young development company based in Bihar, India, owned and managed by Vicky who have a good amount of experience in Information Technology, Management and other related fields. We provide technical and creative services ranging from Internet Marketing to Communication maneuver. We are also skilled in website development which includes brand promotion, web designing and software development.

    best seo company in patna
    digital marketing company in patna
    best website design company in patna

    affordable seo service in patna
    website optimization in patna
    educational internet marketing company patna

    social media marketing company patna
    real estate seo company in patna
    ecommerce seo company patna

  12. The factor of salts/forte is to prevent an attacker from being able to concurrently assault numerous hashes with the same salt. The younger development business enterprise primarily based in Master Thesis Writing Service USA, owned and managed through Vicky who has a very good quantity of enjoying in facts technology, control, and other related fields.

  13. 90minup ข่าวกีฬา ฟุตบอล ผลบอล วิเคราะห์บอล พรีเมียร์ลีก ฟุตบอลไทย

  14. This is a really helpful article. It helped me gain more amount of knowledge. I must I have read a lot of articles on this topic but this one caters to my queries in the best way.
    Sql server dba online training

  15. For those seeking Custom Nursing Essay Writing Service that are 100% original we have plagiarism software that the company utilizes to confirm the level of originality even when offering nursing case study writing services.

  16. Through the assistance of our Write My Research Papers, you will get the best assignment help that will earn you good grades.Order Assignment Writing Help services from us and benefit from the knowledge and experience of professionals in different academic fields.

  17. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
    Software testing online training
    Software testing certification training
    Software testing online course
    Software testing training course

  18. just make it bit longer. harder to remember but more secure
    john | easybuilder.pro

  19. An exceptional Buy College Research Paper will ensure that the client gets only the best quality Best Writing Services work that meets the standards of the Dissertation Writing Services.

  20. ไม่อยากพลาดโอกาศดีๆต้องมาเล่นเกมยิงปลาได้เงินจริงที่นี่เท่านั้น

  21. My Prepaid Centers is the only site that creates the best and the most useful card activation service which make you benefit from the activation in your card with just one minute challenge.You can easily fill out the basic information about your myprepaidcenter card and as soon you take a look again to the site your card will get activated.

  22. A secure password is very important to us because through this we can secure our data and save from hackers and if we do not manage it, we can lose our data which can be stolen by hackers. So, always use strong password so that we can save our personal content. Coursework writing services.

  23. your blog are really helpful for all testers and beginners.this all provided knowledge are unique than other testing blog. Performance Testing Framework are lovely explain.keep updating,Thanks
    Software Testing Training in Chennai | Software Testing Training in Anna Nagar | Software Testing Training in OMR | Software Testing Training in Porur | Software Testing Training in Tambaram | Software Testing Training in Velachery

  24. By - downloading a new antibodies to any persevering, It helps that individual (Coach Outlet Clearance Sale) body's defense mechanisms deal with the problem since improve their potential for recovery. Since the plasma televisions meant for (Yeezy Boost 350 Cheap) hav 888 isn't likely to originated from electricity contributor, Takeda have the ability to initially build the treatment inside segregated house in just their particular manufacturing unit (Coach Outlet Online) in atlanta, With design output (Michael Kors Outlet Store) of it shouldn't adversely (Ray Ban New Wayfarer Polarized) consequences in order to Takeda its definitely produce several plasma display panels based strategies.Treatment (Cheap Yeezy Shoes Sale) options are perhaps considerable, Daily book marking medicinal (Ray Ban Outlet) drugs that a majority of thousand consequentlys of people (Cheap Yeezys For Sale) who have scarce problematic health problems depend on normal almost, Pointed out medical professional. Chelsea Morabito, Takeda


Copyright notice

© André N. Klingsheim and www.dotnetnoob.com, 2009-2018. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to André N. Klingsheim and www.dotnetnoob.com with appropriate and specific direction to the original content.

Read other popular posts