How To Calculate The MD5 Hash

As you know, you shouldn’t store passwords and other sensitive data in plain text. A good approach is to store the data’s MD5 hash.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

publicstaticStringcalcMD5(Strings){

try{

MessageDigest digest=java.security.MessageDigest.getInstance("MD5");

digest.update(s.getBytes());

bytemessageDigest[]=digest.digest();

StringBuffer sb=newStringBuffer();

for(inti=0;i&lt;messageDigest.length;i++){

byteb=messageDigest[i];

Stringhex=Integer.toHexString((int)0x00FF&amp;b);

if(hex.length()==1){

sb.append("0");

}

sb.append(hex);

}

returnsb.toString();

}

catch(NoSuchAlgorithmExceptione){

// exception

}

return"";

}

For example, instead of storing the password 1234 in plain text, you would store 81dc9bdb52d04dc20036dbd8313ed055. In order to authenticate, you generate the MD5 hash from the user input and then you compare both hashes.

1

2

3

Stringpassword="1234";

calcMD5(salt+password);

// the result is 81dc9bdb52d04dc20036dbd8313ed055

To increase security, you should add a salt before generating the MD5 hash. A salt is a small string containing random characters that are not known by the user.