MD5 calculation via Integer.toHexString - Android java.lang

Android examples for java.lang:Integer

Description

MD5 calculation via Integer.toHexString

Demo Code

import android.location.Location;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main{

    public static String calcMD5(String s) {
        try {/*from  ww w  . j  a  v  a2  s  .com*/
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < messageDigest.length; i++) {
                byte b = messageDigest[i];
                String hex = Integer.toHexString((int) 0x00FF & b);
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // exception
        }
        return "";

    }

}

Related Tutorials