Java MD5 String md5(String value)

Here you can find the source of md5(String value)

Description

md

License

Apache License

Declaration

public static String md5(String value) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private final static String MD5 = "MD5";
    private final static String CHARSET = "UTF-8";

    public static String md5(String value) {
        return byte2hex(digest(value, MD5));
    }//from w w  w  . j  ava  2s .  c  o m

    public static String byte2hex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] digest(String value, String algorithm) {
        if (value == null || "".equals(value.trim())) {
            return null;
        }

        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            bytes = md.digest(value.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            //NOP
        } catch (UnsupportedEncodingException e) {
            //NOP
        }

        return bytes;
    }
}

Related

  1. md5(String txt)
  2. md5(String userPass)
  3. md5(String value)
  4. md5(String value)
  5. md5(String value)
  6. md5(String... args)
  7. MD5(String... texts)
  8. md52(String string)
  9. MD5_HEX(String source)