Tuesday, November 13, 2018

Java MD5 Hashing Example

We can use MessageDigest to get the MD5 hashing of byte array:

private byte[] digestMd5(byte[] bytesOfMessage) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(bytesOfMessage);
        return thedigest;
    }


We can use the following to convert Java object to byte array:

public  byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}

For MimeMessage, we can use the following:

Message msg=...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
msg.writeTo(baos);
byte[] bytes = baos.toByteArray();

We can convert the byte array into hex string:

  private String convertByteArrayToHexString(byte[] bytearray) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytearray.length; i++) {
            String hex = Integer.toHexString(0xff & bytearray[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        System.out.println("Digest(in hex format):: " + hexString.toString());
        return hexString.toString();
    }