Can I use Object#hashCode to store the hash of a password?

To save a file i defined the following method

public int encrypt(String fileName, String password) {
   return (fileName.concat(password)).hashCode();
}

This returns a hashvalue that is stored in a file. Whenever the user wants to access the file, he enters the password, and if the same hash is generated, he can access the file.

I suppose this isn’t really safe, but how safe it is? How high is the chance that String#hashCode generates the same hash with two different inputs?

EDIT:

According to your answers I changed the code:

public String encrypt(String password) {
        String hash = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("SHA-512");
            byte [] digest = md5.digest(password.getBytes("UTF-8"));
            hash = Arrays.toString(digest);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hash;
    }

So it should be better now??

Answer

This is a bad idea – you should use a normal cryptographic hash such as SHA-1, just as NullUserException says.

However, it would be portable – the docs for String.hashCode() state the algorithm explicitly. Any JRE implementing the docs properly should give the same hash code. However, because of the way hashCode()‘s algorithm works, it’s pretty easy to find a string which will generate any particular hash code – even one starting with a specific prefix – so an attacker who knew the hash could attack your application very easily. Cryptographic hashes are designed to make it hard to engineer a key to match a particular hash.

Leave a Reply

Your email address will not be published. Required fields are marked *