3

I am attempting to port some of my code over from Python to Java, and it is off to a bit of a rough start as I am not nearly as familiar with Java as I am python. The basic thing I am trying to do is replicate a process as shown here:

import hashlib
myVar = hashlib.md5("Test")
#Which is'\x0c\xbcf\x11\xf5T\x0b\xd0\x80\x9a8\x8d\xc9Za['
#Then proceed to do base64 encoding
base64.encodestring(myVar)
#Which then gives the output of 'DLxmEfVUC9CAmjiNyVphWw==\n'

However, I cannot replicate this process in Java, as every method I have found gives me the hexdigest of the md5 hash rather than what I need. I have tried numerous things to convert that hex back into what I need to get an identical base64 result, but I have had no luck.
Are there any methods that would help me with this process?
As a note, I am using Android Studio if that matters any.

1 Answers1

2

I'm guessing that you weren't converting your java string to the correct encoding before passing it through the digest. I'll use UTF-8 since it matches what python would be using.

Combining the answers from Base64 Encoding in Java and How can I generate an MD5 hash? seems pretty simpleand seems to work for me:

import java.security.MessageDigest;
import org.apache.commons.codec.binary.Base64;

public class md5test {
    public static void main(String[] args) throws Exception {

        String yourString = "Test";
        byte[] bytesOfMessage = yourString.getBytes("UTF-8");

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(bytesOfMessage);

        byte[] encodedBytes = Base64.encodeBase64(thedigest);
        System.out.println("encodedBytes " + new String(encodedBytes));
    }
}

It prints encodedBytes DLxmEfVUC9CAmjiNyVphWw==

Community
  • 1
  • 1
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187