---
SHA-{1,2} are vulnerable to length extension attacks, because of the way their Merkle-Damgard construction works. Basically, if you have the result HASH(X), you can calculate HASH(X+P), knowing only 'HASH(X)', without knowing 'X' itself. This is problematic because it means you can effectively "extend" some cryptographically hashed data with an arbitrary suffix.
You can immunize SHA-2 in one of two ways to a length extension attack:
- Truncate the hash value. For example, use SHA-512, but truncate the result to 256 bits (this is called "SHA-512/256"). This works because the output of your HASH function which is 256-bits, cannot be reused as the initial starting state for a new round of HASH (e.g. SHA-512 needs a 512-bit starting value, but the output is only 256, so this makes it impossible)
- Although it is not standard SHA-2 anymore, you can use a trick from Neils Ferguson and John Kelsey (from 2001!) to immunize it -- simply XOR a constant into the final block round before running the final compression function. Unfortunately this suggestion was not adopted for SHA-2: http://www.cs.utsa.edu/~wagner/CS4363/SHS/dfips-180-2-commen...
Alternatively just use a modern hash design like BLAKE2, SHA-3, or a number of others -- these avoid the entire problem. I'd suggest just sticking to one of those two.
If I had to rank those three hash functions, SHA-2 wouldn't be in last place.