Friday, August 19, 2016

How to encrypt string in Java


Security is important for Business to assurance that you have all proper security systems in place. Encrypting user related information like phone number, password, credit card always assure that their information are safe and secure.  Almost all modern applications need, in one way or another, encryption plays vital role to empower the business. 

The MD5 algorithm is a widely used hash function producing a 128-bit hash value. So, we will create a class with single method to get encrypted value of a String.



import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;

public class md5Hash {
    public static String getEncrypted(String password) {
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("MD5");
            m.update(password.getBytes(), 0, password.length());
            return (new BigInteger(1, m.digest()).toString(16));
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(md5Hash.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}

Now, you can simply call this method as shown below to get encrypted string 

String encrypted = md5Hash.getEncrypted(password);

No comments:

Post a Comment