Android : How to create HMAC MD5 string? [closed]

拈花ヽ惹草 提交于 2019-11-29 07:24:18

Define 'not working'. Exception? Output not as expected?, etc.

One obvious thing is that you are processing the same data twice:

mac.update(sData.getBytes());
bytes = mac.doFinal(sData.getBytes());

To process all data in one pass, just use doFinal() (assuming it's not too big). Another thing that can be wrong is the format of the key: what is the format of String sKey. Ideally you should be using a BASE64 encoded string, not calls to getString().

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 ;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!