When should I use SHA-1 and when should I use SHA-2?

Majd picture Majd · Feb 15, 2011 · Viewed 27.8k times · Source

In my c# application, I'm using RSA to sign files before being uploaded on the database of my company by the person who is uploading and here I have to choose SHA-1 or SHA-2 for computing the hash.
As any other component in programming, I know that there must be a "use this here" and "use that there" for the two of them.
So, When this? and when that?

EDIT:
My question is: What is the difference regarding performance? and not regarding security, as I already know that SHA-2 is more solid secure than SHA-1.
In this Link a comparison between different types of SHA-2 noting when to use SHA-512 and when not in the end. I need a similar argument about SHA-1 and SHA-2.

Answer

Thomas Pornin picture Thomas Pornin · Feb 15, 2011

Use SHA-2. Always. SHA-1 shall be reserved to situations where SHA-2 cannot be used due to interoperability issues with legacy code.

There is no performance issue until actual measures have been performed. Hash functions are fast. In most situations, hash function performance has only negligible impact; even detecting it could prove difficult. Security comes first. Since weaknesses have been found in SHA-1, using it nonetheless requires some robust justification. Using SHA-256 will not be questioned; this is the "default choice". But if you use SHA-1, prepare to be criticized.

Note that there are four functions known as "SHA-2": SHA-224, SHA-256, SHA-384 and SHA-512. SHA-224 and SHA-256 are the same function, save for an internal parameter (the "initial value") and the output size (SHA-224 output size is 28 bytes, whereas SHA-256 offers 32 bytes); they have the same performance characteristics. Similarly, SHA-384 and SHA-512 are the same function performance-wise. SHA-512 uses 64-bit arithmetic operations and is faster than SHA-256 on platforms which offer 64-bit opcodes; on 32-bit platforms, SHA-256 will be faster (note: on 32-bit x86 with native code, it is possible to use the SSE2 opcodes and their 64-bit computing abilities, hence some native code implementations of SHA-512 will be faster than SHA-256 in 32-bit mode; the OpenSSL code does that; but, as far as I know, the SHA-512 implementation in .NET is "managed code"). Also, all the SHA-* functions have some basic granularity, because they process data by chunks: for SHA-256, chunks are 64-byte long, whereas SHA-512 uses 128-byte chunks; when hashing very short data elements, the higher SHA-512 granularity correspondingly lowers its performance. Finally, SHA-256 (on a 32-bit platform) is likely to yield smaller code (i.e. use less L1 cache on the CPU).

So, when in doubt, use SHA-256. If you plan on using SHA-1 then you should doubt.

If you want to use a hash function for a non-cryptographic usage (i.e. the weaknesses are not a problem for you) then, instead of SHA-1, consider MD4.