0

I'm trying to compare passwords in java coming from a web service.

I invoke the service from command line with the following:

curl -d '[{"usr":"joe","password":"joe"}]' http://mydomain.com:8080/myservice/login

I parse the JSON and pass the password to a hash method.

My hashing method is as follows:

 private String createHash(String password){

    byte[] bytesOfMessage = null;
    try {
        bytesOfMessage = password.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String thedigest = md.digest(bytesOfMessage).toString();
    System.out.println("passed in: "+thedigest);

    return thedigest;
}

The problem is that the hash that is printed is different everytime I invoke this method with the exact same password. How can I have the passwords come out with the same hash so I can compare the passwords and authenticate a user?

Thanks!

Atma
  • 29,141
  • 56
  • 198
  • 299

2 Answers2

3

the digest() method is returning you a byte[], and the toString() method on byte[] is printing out the object identity of the byte array, not the content. generally, in order to print out the results of a byte[], you need to convert the bytes to a printable string (often using hex encoding or base64 encoding). hex encoding is frequently used for md5 checksums, example here.

Community
  • 1
  • 1
jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • 1
    A simple call to `Arrays.toString(byte[])` will suffice if you just want to see the contents of the byte array, but is probably not appropriate for storing in a database if that's what you're after. – Alex Sep 04 '12 at 18:09
0

You can try with base64.I have given the example

public String encrypt(String plaintext) throws Exception {

        MessageDigest messageDigest = null;
        String hash=null;

        try{
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(plaintext.getBytes("UTF8"));
            byte[] raw = messageDigest.digest();
            hash = new String(Base64.encode(raw));


        }catch(Exception nsa){
        throw new Exception();
        }

            return hash;

}
Debopam Mitra
  • 1,842
  • 4
  • 27
  • 51
Biswajit
  • 2,434
  • 2
  • 28
  • 35