1

Is there a way I can shorten a sha1 hash to store in a database, and then upon retrieval perform a unshorten function on it to display the original?

I am not sure this is possible, my sha1 hashes are currently 40 characters long.

Thanks

hadley
  • 621
  • 3
  • 7
  • 12
  • 1
    Possible duplicate of [Storing SHA1 hash values in MySQL](http://stackoverflow.com/q/614476/53114). – Gumbo May 26 '12 at 20:59
  • 1
    If you are using SHA1 to hash passwords, consider using something like SHA256 instead, since SHA1 is compromised. Also, why do you need to shorten the hash in the DB? Truncating hashes isn't always a safe operation... – Oleksi May 26 '12 at 21:01
  • Why would you want to do this? It could only make your passwords less secure. – GordonM May 26 '12 at 21:04
  • 2
    I am not using it to store passwords at all. – hadley May 26 '12 at 21:07
  • 3
    `pack('H', $asciiHash);` will convert your 40 byte ascii representation to a 20 byte binary one, and `unpack('Hascii', $binaryHash);` will convert it back again, but if you're really bothered about saving 20 bytes here and there I suggest you have more important things to worry about... – DaveRandom May 26 '12 at 21:07
  • Haha and people downvote on the compromise of a security concern when my question has nothing to do with security I have a valid use for using sha1 and wanting to truncate the string – hadley May 26 '12 at 21:08
  • @DaveRandom I have a table of around 5million rows containing just sha1 hashes, I don't think I have anything to worry about, about wanting to save space. – hadley May 26 '12 at 21:09
  • @hadley fair enough - 20 bytes is as small as you will get without any loss of data (since SHA-1 is a 160-bit hash), you can actually get `sha1()` to return the binary version by passing `TRUE` as the second argument – DaveRandom May 26 '12 at 21:10
  • You would need to convert your database fields to (assuming MySQL) `VARBINARY`, `BLOB` etc for storage – DaveRandom May 26 '12 at 21:12
  • @hadley [Here's a little demo](http://codepad.org/yTQfMsKA) – DaveRandom May 26 '12 at 21:20
  • @DaveRandom thanks this is awesome and has helped me understand alot :) – hadley May 26 '12 at 22:10

0 Answers0