Java MD5 String md5(String str)

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

Description

md

License

Apache License

Declaration

public static String md5(String str) 

Method Source Code


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

import java.security.MessageDigest;

public class Main {

    public static String md5(String str) {
        String md5 = encode(str, "MD5").toLowerCase();
        return md5;
    }// w  w  w  .j a  v  a  2  s  .c  o  m

    private static String encode(String str, String type) {
        try {
            MessageDigest alga = MessageDigest.getInstance(type);
            alga.update(str.getBytes());
            byte digesta[] = alga.digest();
            String hex = byte2hex(digesta);
            // String hex2 = byte2hex2(digesta);
            // if (!hex.equals(hex2)) {
            // System.out.println("str:" + str);
            // }
            return hex;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static String byte2hex(byte b[]) {
        StringBuilder sb = new StringBuilder();
        for (int n = 0; n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                // hs = hs + "0" + stmp;
                sb.append("0");
            }
            sb.append(stmp);
            // else {
            // // hs = hs + stmp;
            // }
        }

        return sb.toString().toUpperCase();
    }

    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
}

Related

  1. md5(String src)
  2. md5(String src)
  3. md5(String src)
  4. md5(String srcStr)
  5. md5(String str)
  6. MD5(String str)
  7. md5(String str)
  8. md5(String str)
  9. md5(String str)