Dibawah ini adalah fungsi statis untuk memanggil md5 hash dengan fungsi core java MessageDigest(), data type tersebut menghasilkan return md5 hash dengan data type String plaintext
private static String md5hash(String e) {
String result = "null";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(e.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
result = sb.toString();
} catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
Simpan script java dibawah ini dengan nama HelloWorld.java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
class HelloWorld {
private static String md5hash(String e) {
String result = "null";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hash = md.digest(e.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder(2 * hash.length);
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
result = sb.toString();
} catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public static void main(String[] args) {
String text = "myplaintext";
String md5_hash = md5hash(text);
System.out.println("md5 hash result : "+md5_hash+"\n");
}
}
Maka dari diatas akan menghasilkan md5 hash "3c5d21f4241582748caf9d6f6507167e" dari input string "myplaintext".
Jalankan script java : java HelloWorld.java, hasilnya:
md5 hash result : 3c5d21f4241582748caf9d6f6507167e