In this tutorial, I am going to show you how to use Java MD5 Encryption.
Java MD5 Encryption :
The below example generate a MD5 encryption (generating hash value) for a given password (String).
JavaMD5Example.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JavaMD5Example {
public static String getMD5EncryptedValue(String password) {
final byte[] defaultBytes = password.getBytes();
try {
final MessageDigest md5MsgDigest = MessageDigest.getInstance("MD5");
md5MsgDigest.reset();
md5MsgDigest.update(defaultBytes);
final byte messageDigest[] = md5MsgDigest.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : messageDigest) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
password = hexString + "";
} catch (final NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
return password;
}
public static void main(String[] args) {
System.out.println(getMD5EncryptedValue("chandra123"));
System.out.println(getMD5EncryptedValue("chandra123"));
}
}
Output :
Terminal
b4a3f7314b7b5096b920a3a8c1ef0ac2
b4a3f7314b7b5096b920a3a8c1ef0ac2