Calculate MD5 for string and format with String.format - Android java.security

Android examples for java.security:MD5

Description

Calculate MD5 for string and format with String.format

Demo Code

import android.text.SpannableStringBuilder;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static String toMD5(String target) {
        String result;//  w  w  w . ja  v a 2 s  . c om
        StringBuilder stringBuilder;
        MessageDigest md5;
        byte[] digest;

        if (target != null && target.length() > 0) {
            try {
                stringBuilder = new StringBuilder();
                md5 = MessageDigest.getInstance("MD5");
                md5.update(target.getBytes());
                digest = md5.digest();
                for (byte b : digest) {
                    stringBuilder.append(String.format("%02x", b));
                }

                result = stringBuilder.toString();
            } catch (Exception e) {
                result = "";
            }
        } else {
            result = "";
        }

        return result;
    }

}

Related Tutorials