Question

develop a algorithm to implement MD5 in Java to encrypt/hash passwords with salt.

develop a algorithm to implement MD5 in Java to encrypt/hash passwords with salt.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

public class SaltedMD5Example

{

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException

    {

        String passwordToHash = "password";

        byte[] salt = getSalt();

         

        String securePassword = getSecurePassword(passwordToHash, salt);

        System.out.println(securePassword); //Prints 83ee5baeea20b6c21635e4ea67847f66

         

        String regeneratedPassowrdToVerify = getSecurePassword(passwordToHash, salt);

        System.out.println(regeneratedPassowrdToVerify); //Prints 83ee5baeea20b6c21635e4ea67847f66

    }

     

    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

            md.update(salt);

            //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) {

            e.printStackTrace();

        }

        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

        sr.nextBytes(salt);

        //return salt

        return salt;

    }

}

Add a comment
Know the answer?
Add Answer to:
develop a algorithm to implement MD5 in Java to encrypt/hash passwords with salt.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT