DigestUtil

package cn.it.shop.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class DigestUtil {

private static String encodingCharset = "UTF-8";

/**
 * @param aValue
 * @param aKey
 * @return
 */
public static String hmacSign(String aValue, String aKey) {
    byte k_ipad[] = new byte[64];
    byte k_opad[] = new byte[64];
    byte keyb[];
    byte value[];
    try {
        keyb = aKey.getBytes(encodingCharset);
        value = aValue.getBytes(encodingCharset);
    } catch (UnsupportedEncodingException e) {
        keyb = aKey.getBytes();
        value = aValue.getBytes();
    }

    Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
    Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
    for (int i = 0; i < keyb.length; i++) {
        k_ipad[i] = (byte) (keyb[i] ^ 0x36);
        k_opad[i] = (byte) (keyb[i] ^ 0x5c);
    }

    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {

        return null;
    }
    md.update(k_ipad);
    md.update(value);
    byte dg[] = md.digest();
    md.reset();
    md.update(k_opad);
    md.update(dg, 0, 16);
    dg = md.digest();
    return toHex(dg);
}

public static String toHex(byte input[]) {
    if (input == null)
        return null;
    StringBuffer output = new StringBuffer(input.length * 2);
    for (int i = 0; i < input.length; i++) {
        int current = input[i] & 0xff;
        if (current < 16)
            output.append("0");
        output.append(Integer.toString(current, 16));
    }

    return output.toString();
}

/**
 * 
 * @param args
 * @param key
 * @return
 */
public static String getHmac(String[] args, String key) {
    if (args == null || args.length == 0) {
        return (null);
    }
    StringBuffer str = new StringBuffer();
    for (int i = 0; i < args.length; i++) {
        str.append(args[i]);
    }
    return (hmacSign(str.toString(), key));
}

/**
 * @param aValue
 * @return
 */
public static String digest(String aValue) {
    aValue = aValue.trim();
    byte value[];
    try {
        value = aValue.getBytes(encodingCharset);
    } catch (UnsupportedEncodingException e) {
        value = aValue.getBytes();
    }
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
    return toHex(md.digest(value));

}

public static void main(String[] args) {
    System.out.println(DigestUtil.hmacSign("11111", "abc"));
    System.out.println(DigestUtil.hmacSign("11112", "abc"));
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值