How can encrypt a password in Java..?

md5 Hash Encrypt in java
How Encrypt Value in md5

There are many such hashing algorithms in java also, which can prove really effective for password security. In this post, I will discuss some of them.

Note: Please remember one thing that when password hash is generated and stored in database, you can not convert it and back to it original password. Each time user login into application, you have to regenerate password hash again, and match with hash stored in database. So, if user forgot his/her password, you will have to send him a temporary password and ask him to change it with his new password. It’s common now-a-days, right..?




The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check data integrity. MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. An MD5 hash is typically expressed as a 32-digit hexadecimal number

Using MessageDigest Class

You need to import someclasses for using md5 The idea is to first instantiate MessageDigest with the kind of algorithm you want to use as argument to the Singleton:


Below is an example which generates hash for a password and then verifies it:

public static String passwordgn(String pass)
String passwordToHash =pass;
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance(“MD5”);
//Add password bytes to digest
//Get the hash’s bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
//Get complete hashed password in hex format
generatedPassword = sb.toString();
catch (Exception e)
return pass;}

Above example is quite straight forward. When we calling a function passwordgn(String pass) passing a value string type in parameter it return the encrypt value. In md5() method we used class’s object to generate Md5 hash.

Console Output


Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *