This week's book giveaway is in the Android forum. We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line! See this thread for details.

Hi I have used MessageDigest class to encrypt password and then store it in the database. I know I can compare the password with what user enters by encrypting what user enters but I also want to be able to read and display actual password. How do I decrypt that.

Following is the simple code I am using to encrypt

md = MessageDigest.getInstance( "SHA-1" ); md.update( plainText.getBytes("UTF-8") ); (plainText is what needs to be converted)

byte[] raw = md.digest() ;

String hash = ( new BASE64Encoder()).encode( raw ) ;

return hash ;

Now I want to know with this "hash" value provided how can I get back my plain text. Thanks Imad

SHA-1 is not (technically) "encryption" it is a hash. One of the definitions of a hash is that it cannot be reversed (which is why you use it for passwords - so that -nobody- (not even the administrator) can possibly know a user's password).

A hash is a numerical representation of a set of data. Since a hash algorithm has a fixed numerical size, there must be more than one sets of data that could end up being represented by the same numerical value (in fact there should be _infinite_ sets of data that would represent the same numerical value - save for the fact that 'infinite' amounts of data present an impossible computuational problem).

However, finding another set of data to represent a given hash value will be computationally difficult, making it technologically impossible (nearly) to find another set of data that matches one represented by the hash value. Think of it like this:

data hash ab 1 cd 2 ef 3 ... ... st 1

In this case, the hash value is a number from 1-9, when we get to "st", we run out of possible hash values (we've used all 9 of them), so we have to duplicate one that's already been used.

Of course, a good hash algorithm will use very large numbers, and will take an unlimited (arbitrarily large) stream of possible data to compute the hash value (instead of just a set of 2 letters). So the good hash algorithm will take a variable amount of data, and compute a fixed-length numerical value for that amount of data.

The consequence is you cannot reverse the hash. You might be able to brute-force the hash value (try random combinations of bits/bytes and pass them through the hash), but that would only guarantee that you would find _1_ of the possible values for the hash - not necessarily the one that was used to generate the hash. You could also hash words from a password dictionary (commonly used passwords), and see if one of them generated a duplicate hash, but both of those methods might take large amounts of time (days, weeks, even years) in order to return results.