MD5工具类
public class MD5Util { /* * @Desccription md5加密 */ public static String encrypt(String plainText) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes());//调用内部方法 byte b[] = md.digest();//加密成二进制 return CryptoUtil.byte2Hex(b);//调用工具类转换成String } /** * 签名字符串 * @param text 需要签名的字符串 * @param sign 签名结果 * @param key 密钥 * @param inputCharset 编码格式 * @return 签名结果 */ public static boolean verify(String text, String sign, String key, String inputCharset) { text = text + key; String mysign = DigestUtils.md5Hex(getContentBytes(text, inputCharset)); if(mysign.equals(sign)) { return true; } else { return false; } } /** * 签名字符串 * @param text 需要签名的字符串 * @param key 密钥 * @param inputCharset 编码格式 * @return 签名结果 */ public static String sign(String text, String key, String inputCharset) { text = text + key; return DigestUtils.md5Hex(getContentBytes(text, inputCharset)); } /** * @param content * @param charset * @return * @throws * @throws UnsupportedEncodingException */ private static byte[] getContentBytes(String content, String charset) { if (charset == null || "".equals(charset)) { return content.getBytes(); } try { return content.getBytes(charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset); } } }
工具类
/* * @Desccription byte 转成string * @Date 2018/1/22 * @Created by yaowj * @Param b * @Return java.lang.String */ public static String byte2Hex(byte[] b) { StringBuilder hs = new StringBuilder(); String stmp; for (int n = 0; b != null && n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) hs.append('0'); hs.append(stmp); } return hs.toString().toUpperCase(); }
应用
String md5Pwd = ""; try{ md5Pwd = MD5Util.encrypt(param.getPassword()); }catch (Exception ex){ log.error("mgr_user_save_0005,密码md5加密失败", ex); throw new GCloudException("server_token_get_0004::password encrypt error"); }