1

我试图使用 md5 生成 HMAC,一切似乎都很完美,但它显示出意外的错误

代码如下

public String calcHmac(String src) throws Exception {

        String key = "PFhNTD48VUlEPlNYWUFOR0VUPC9VSUQ+PEVUUkFOQVVUSD48WFNQUk9MRT5BbGw8L1hTUFJPTEU+PFhTUFNlY3VyaXR5SUQ+MzMzPC9YU1BTZWN1cml0eUlEPjxYU1BTZWN1cml0eUlEPjk5NzwvWFNQU2VjdXJpdHlJRD48WFNQU2VjdXJpdHlJRD5HQjwvWFNQU2VjdXJpdHlJRD48WFNQU2VjdXJpdHlJRD5YMDM8L1hTUFNlY3VyaXR5SUQ+PFhTUFNlY3VyaXR5SUQ+WDAxPC9YU1BTZWN1cml0eUlEPjxYU1BSZWNpcGllbnQ+NDlBQ0NULVNZQU5HRVRSQU48L1hTUFJlY2lwaWVudD48L0VUUkFOQVVUSD48L1hNTD4=";
        SecretKeySpec keySpec = new SecretKeySpec(
                key.getBytes(),
                "HmacMD5");

        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(keySpec);
        byte[] result = mac.doFinal(src.getBytes());
        return Hex.encodeHexString(result);   
    }
4

1 回答 1

1

尝试这个

 public static String sStringToHMACMD5(String s, String keyString)
    {
        String sEncodedString = null;
        try
        {
            SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacMD5");
            Mac mac = Mac.getInstance("HmacMD5");
            mac.init(key);

            byte[] bytes = mac.doFinal(s.getBytes("ASCII"));

            StringBuffer hash = new StringBuffer();

            for (int i=0; i<bytes.length; i++) {
                String hex = Integer.toHexString(0xFF &  bytes[i]);
                if (hex.length() == 1) {
                    hash.append('0');
                }
                hash.append(hex);
            }
            sEncodedString = hash.toString();
        }
        catch (UnsupportedEncodingException e) {}
        catch(InvalidKeyException e){}
        catch (NoSuchAlgorithmException e) {}
        return sEncodedString ;
    }

这肯定会帮助你。

谢谢

于 2012-07-18T10:23:50.467 回答