MD5

public class Md5Utils {


	public 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) {
		}
		return null;
	}

	public static byte[] hmac(String data, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
		Mac mac = Mac.getInstance("HmacSHA256");
		// get the bytes of the hmac key and data string
		byte[] secretByte = secret.getBytes("UTF-8");
		byte[] dataBytes = data.getBytes("UTF-8");
		SecretKey secretKey = new SecretKeySpec(secretByte, "HMACSHA256");
		mac.init(secretKey);
		return mac.doFinal(dataBytes);
	}

	public 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 data, String key) {
		try {
			return new String(toHex(hmac(data, key)).getBytes("UTF-8"), "UTF-8");
		} catch (Exception e) {
			return data;
		}
	}
	
	/**
	 * 返回32位大写MD5�?
	 * @param content
	 * @return  异常返回null 转换成功返回 32位大写MD5
	 */
	private static String getEncode32MD5(String content){
		 try {
             MessageDigest digest = MessageDigest.getInstance("MD5");
             digest.update(content.getBytes("UTF-8"));
             StringBuilder builder = new StringBuilder();
             for (byte b : digest.digest()) {
                     builder.append(Integer.toHexString((b >> 4) & 0xf));
                     builder.append(Integer.toHexString(b & 0xf));
             }
           return builder.toString().toUpperCase();
     } catch (Exception e) {
    	 return null;
     }
	}
	private final static String salt = "sunqingyun";
	public static String get32MD5(String content){
		return getEncode32MD5(content+salt);
	}

	public static String getLessonZipNameMD5(String content){
		return getEncode32MD5(content);
	}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值