Java MD5 Byte Array md5(byte[] input)

Here you can find the source of md5(byte[] input)

Description

md

License

Apache License

Declaration

public static String md5(byte[] input) 

Method Source Code


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

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

public class Main {
    public static String md5(byte[] input) {
        return encryptPassword(input, "md5");
    }/*from w  w w  .j a  va2s .  c o  m*/

    public static String md5(String text) {
        return md5(text, "utf-8");
    }

    public static String md5(String text, String encoding) {
        return encryptPassword(text, encoding, "md5");
    }

    public static String md5(String text, int length) {
        String result = md5(text);
        if (result.length() > length)
            result = result.substring(0, length);
        return result;
    }

    private static String encryptPassword(String password, String encoding, String algorithm) {
        try {
            byte[] unencodedPassword = password.getBytes(encoding);
            return encryptPassword(unencodedPassword, algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    private static String encryptPassword(byte[] unencodedPassword, String algorithm) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            return null;
        }
        md.reset();
        md.update(unencodedPassword);
        byte[] encodedPassword = md.digest();
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }
        return buf.toString();
    }
}

Related

  1. md5(byte[] data)
  2. md5(byte[] data)
  3. md5(byte[] data)
  4. md5(byte[] input)
  5. md5(byte[] input)
  6. md5(byte[] input)
  7. md5(byte[] md5)
  8. md5(byte[] param)
  9. md5(byte[] source)