Java MD5 String MD5(String text)

Here you can find the source of MD5(String text)

Description

MD

License

Open Source License

Declaration

public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        return messageDigest(text, "MD5");
    }//from   w  w  w.  j  a  v  a 2  s . co  m

    public static String messageDigest(String text, String algorithm)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        // md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md.update(text.getBytes("UTF-8"), 0, text.length());
        //        // SHA-512 --> 64 bytes / 128 hex numbers.
        //        byte[] sha1hash = new byte[64];
        //        sha1hash = md.digest();
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }

    private static String convertToHex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9)) {
                    buf.append((char) ('0' + halfbyte));
                } else {
                    buf.append((char) ('a' + (halfbyte - 10)));
                }
                halfbyte = data[i] & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }
}

Related

  1. md5(String text)
  2. md5(String text)
  3. md5(String text)
  4. MD5(String text)
  5. md5(String text)
  6. md5(String text)
  7. MD5(String text)
  8. MD5(String text)
  9. md5(String text)