MD5加密算法工具类

来源:互联网 发布:js中的if else 编辑:程序博客网 时间:2024/05/16 17:56
public class MD5Helper {    private static byte[] hex = new byte[]{'0', '1', '2', '3', '4', '5', '6',            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};    /**     * 把String字符串转化为MD5摘要码     *     * @param rawString 原始字符串     * @return     */    public static String getMD5(String rawString) {        String md5String = null;        try {            MessageDigest md5 = MessageDigest.getInstance("MD5");            md5.update(rawString.getBytes());            md5String = convertToHexString(md5.digest());        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }        if (null != md5String) {            return md5String.toUpperCase();        }        return md5String;    }    /**     * 把文件转化为MD5摘要码     *     * @param file     * @return     */    public static String getMD5(File file) {        FileInputStream fis = null;        try {            MessageDigest md = MessageDigest.getInstance("MD5");            fis = new FileInputStream(file);            byte[] buffer = new byte[2048];            int length = -1;            while ((length = fis.read(buffer)) != -1) {                md.update(buffer, 0, length);            }            byte[] b = md.digest();            return convertToHexString(b);        } catch (Exception ex) {            ex.printStackTrace();            return null;        } finally {            try {                fis.close();            } catch (IOException ex) {                ex.printStackTrace();            }        }    }    /**     * 把byte[]数组转换成十六进制字符串表示形式     *     * @param digests     * @return     */    private static String convertToHexString(byte[] digests) {        byte[] md5String = new byte[digests.length * 2];        int index = 0;        for (byte digest : digests) {            md5String[index] = hex[(digest >> 4) & 0x0F];            md5String[index + 1] = hex[digest & 0x0F];            index += 2;        }        return new String(md5String);    }    /**     * @param args     */    public static void main(String[] args) {// TODO Auto-generated method stub        String teString = getMD5("abcdefg");        System.out.println(teString);// 7AC66C0F148DE9519B8BD264312C4D64    }}
0 0