Java MD5 Hash with Salt Example

This Java source code example demonstrates how to secure a password using the MD5 algorithm with salt in Java programming language.
If you are using MD5 hash in your application then consider adding some salt to your security.
The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It’s very simple and straight forward; the basic idea is to map data sets of variable length to data sets of a fixed length.

Java MD5 Hash with Salt Example



public class SimpleMD5Example {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
        String passwordToHash = "test123";
        byte[] salt = getSalt();

        String securePassword = getSecurePassword(passwordToHash, salt);

        String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);

    private static String getSecurePassword(String passwordToHash, byte[] salt) {
        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(passwordToHash.getBytes());
            //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 (NoSuchAlgorithmException e) {
        return generatedPassword;

    //Add salt
    private static byte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException {
        //Always use a SecureRandom generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
        //Create array for salt
        byte[] salt = new byte[16];
        //Get a random salt
        //return salt
        return salt;


Please note that now you have to store this salt value for every password you hash. Because when user login back in the system, you must use only originally generated salt to again create the hash to match with the stored hash. If a different salt is used (we are generating random salt), then generated hash will be different.