123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package com.kmall.admin.haikong.utils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import java.io.UnsupportedEncodingException;
- import java.security.MessageDigest;
- /**
- * Md5加密方法
- *
- * @author cadmin
- */
- public class Md5Utils
- {
- private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
- private static byte[] md5(String s)
- {
- MessageDigest algorithm;
- try
- {
- algorithm = MessageDigest.getInstance("MD5");
- algorithm.reset();
- algorithm.update(s.getBytes("UTF-8"));
- byte[] messageDigest = algorithm.digest();
- return messageDigest;
- }
- catch (Exception e)
- {
- log.error("MD5 Error...", e);
- }
- return null;
- }
- private static final String toHex(byte hash[])
- {
- if (hash == null)
- {
- return null;
- }
- StringBuffer buf = new StringBuffer(hash.length * 2);
- int i;
- for (i = 0; i < hash.length; i++)
- {
- if ((hash[i] & 0xff) < 0x10)
- {
- buf.append("0");
- }
- buf.append(Long.toString(hash[i] & 0xff, 16));
- }
- return buf.toString();
- }
- public static String hash(String s)
- {
- try
- {
- return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
- }
- catch (Exception e)
- {
- log.error("not supported charset...{}", e);
- return s;
- }
- }
- /**
- * MD5加密,返回32位密文
- * @param plainText
- * @return String
- * @throws UnsupportedEncodingException
- */
- public static String encryption(String plainText){
- String re_md5 = new String();
- try {
- MessageDigest md = MessageDigest.getInstance("MD5");
- md.update(plainText.getBytes("UTF-8"));
- byte b[] = md.digest();
- int i;
- StringBuffer buf = new StringBuffer("");
- for (int offset = 0; offset < b.length; offset++) {
- i = b[offset];
- if (i < 0)
- i += 256;
- if (i < 16)
- buf.append("0");
- buf.append(Integer.toHexString(i));
- }
- re_md5 = buf.toString();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return re_md5;
- }
- }
|