package com.zzwtec.wechat.util.security; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by Xin.L on 9/10/15. */ public class EncoderHandler { /** HEX_DIGITS 16进制字符 */ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public static String MD5(String input) { return encrypt(input, "MD5", "UTF-8"); } public static String SHA1(String input) { return encrypt(input, "SHA-1", "UTF-8"); } public static String SHA512(String input) { return encrypt(input, "SHA-512", "UTF-8"); } // 摘要算法加密 private static String encrypt(String input, String algorithm, String encoding) { MessageDigest messageDigest = null; byte[] bytes = null; try { messageDigest = MessageDigest.getInstance(algorithm); bytes = messageDigest.digest(input.getBytes(encoding)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return bytesToHex(bytes); } // bytesToHex private static String bytesToHex(byte[] bytes) { StringBuilder buff = new StringBuilder(); for (byte bt : bytes) { buff.append(HEX_DIGITS[(bt & 0xf0) >> 4] + "" + HEX_DIGITS[bt & 0xf]); } return buff.toString(); } }