Convert SHA1 back to string

2019-07-07 05:22发布

问题:

I have a user model on my app, and my password field uses sha1. What i want is to, when i get the sha1 from the DB, to make it a string again. How do i do that?

回答1:

You can't - SHA1 is a one-way hash. Given the output of SHA1(X), is not possible to retrieve X (at least, not without a brute force search or dictionary/rainbow table scan)

A very simple way of thinking about this is to imagine I give you a set of three-digit numbers to add up, and you tell me the final two digits of that sum. It's not possible from those two digits for me to work out exactly which numbers you started out with.

See also

  • Is it possible to reverse a sha1?
  • Decode sha1 string to normal string

Thought relating MD5, these other questions may also enlighten you:

  • Reversing an MD5 Hash
  • How can it be impossible to “decrypt” an MD5 hash?


回答2:

You can't -- that's the point of SHA1, MDB5, etc. Most of those are one-way hashes for security. If it could be reversed, then anyone who gained access to your database could get all of the passwords. That would be bad.

Instead of dehashing your database, instead hash the password attempt and compare that to the hashed value in the database.



回答3:

If you're talking about this from a practical viewpoint, just give up now and consider it impossible. Finding the original string is impossible (except by accident). Most of the point of a cryptographically secure hash is to ensure you can't find any other string that produces the same hash either.

If you're interested in research into secure hash algorithms: finding a string that will produce a given hash is called a "preimage". If you can manage to do so (with reasonable computational complexity) for SHA-1 you'll probably become reasonably famous among cryptanalysis researchers. The best "break" against SHA-1 that's currently known is a way to find two input strings that produce the same hash, but 1) it's computationally quite expensive (think in terms of a number of machines running 24/7 for months at a time to find one such pair), and does not work for an arbitrary hash value -- it finds one of a special class of input strings for which a matching pair is (relatively) easy to find.



回答4:

SHA is a hashing algorithm. You can compare the hash of a user-supplied input with the stored hash, but you can't easily reverse the process (rebuild the original string from the stored hash).

Unless you choose to brute-force or use rainbow tables (both extremely slow when provided with a sufficiently long input).



回答5:

You can't do that with SHA-1. But, given what you need to do, you can try using AES instead. AES allows encryption and decryption.