Wednesday 10 May 2017

Convert string to MD5 in android

Converting the string into MD5 with this simple class.
import java.security.MessageDigest;
/** * Created by amit rawat on 5/10/2017. */public class MD5 {
    public static String getMd5Key(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte byteData[] = md.digest();
            //convert the byte to hex format
             StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
             sb.append(Integer.toString((byteData[i] & 0xff) + 0x10016).substring(1));
            }
            System.out.println("Digest(in hex format):: " + sb.toString());
            //convert the byte to hex format 
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                String hex = Integer.toHexString(0xff & byteData[i]);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            System.out.println("Digest(in hex format):: " + hexString.toString());
            return hexString.toString();
        } catch (Exception e) {
               }
        return "";
    }
}