18

If I want to save a hash of a certain number of bits, but my hashing algorithm gives me more bits than I need, then what is the safest way to shorten it?

Should I:

  • Just remove the first or last few bits
  • XOR the first or last few bits with the part I'm keeping
  • Do something else

Does it matter how I'm shortening it, or does it depend on the hash algorithm I'm using? Does this reduce the security of the hash (ex.: is a 128-bit hash trimmed to 64 bits worse than a 64-bit hash of the same algorithm)?

5
  • What size do you need and have currently?
    – user72066
    Aug 20, 2015 at 18:18
  • @Revulai: I have 256 bits but need 240 bits.
    – user28763
    Aug 20, 2015 at 18:19
  • What hash is used? Maybe you can use a different one? Is it a selfmade hash?
    – ott--
    Aug 20, 2015 at 19:23
  • @ott: It's SHA-256
    – user28763
    Aug 20, 2015 at 19:24
  • Why do you need to shorten the hash? Aug 20, 2015 at 19:28

2 Answers 2

24

Simply truncating a hash is the common and accepted way to shorten it. You don't need to do anything fancy.

There are plenty of questions here, and on crypto.stackexchange about whether doing this reduces the strength of the hash (see the list of related questions at the bottom). The answer is that No, truncating a hash does not reduce its strength (apart from the obvious that shorter hashes have more collisions).

According to @Reid's answer in [2] and @ThomasPornin's answer in [3], the idea of truncating hashes is fully supported by NIST, in fact SHA-224 is just SHA-256 truncated, SHA-384 is just SHA-512 truncated, etc.


RELATED QUESTIONS

[1] truncated hash for message authentication?

[2] Is truncating a SHA512 hash to the first 160 bits as secure as using SHA1?

[3] Should I use the first or last bits from a SHA-256 hash?

1
  • 5
    SHA-384 is almost the same as SHA-512 truncated; it also uses different constants inside. Also note that to remain compatible with most implementations you should use the leftmost bytes of the resulting hash. Aug 20, 2015 at 20:43
1

Yes, shortening a hash does reduce the security of the hash. An important part of the security of a hashing algorithm is the algorithms collision resistance. This mean that if I hash ThingToHash1 the result (hopefully) won't match the hash for any other input. By truncating the hash, you're increasing the likelihood of a collision because only a subset of the hashing algorithms output need to collide with the output from another input. However, if the occasional collision is acceptable and not harmful to the security of your application it's fine to do. For example, git accepts truncated commit hashes to identify specific commits.

0

You must log in to answer this question.