How to generate HMAC-SHA1 Signature in android?

后端 未结 2 587
甜味超标
甜味超标 2020-12-14 11:17

This is my base String:

        String args =\"oauth_consumer_key=\"+enc(consumerkey) +
                   \"&oauth_nonce=\"+enc(generateNonce()) +
              


        
2条回答
  •  攒了一身酷
    2020-12-14 12:01

    Femi's answer is absolutely correct, however, it wasn't obvious for me what exactly is intval(b). As i understood it's b & 0xFF.

    Also I applied some optimizations (that I found here) and here is my code:

    private static String hmacSha1(String value, String key)
            throws UnsupportedEncodingException, NoSuchAlgorithmException,
            InvalidKeyException {
        String type = "HmacSHA1";
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
        Mac mac = Mac.getInstance(type);
        mac.init(secret);
        byte[] bytes = mac.doFinal(value.getBytes());
        return bytesToHex(bytes);
    }
    
    private final static char[] hexArray = "0123456789abcdef".toCharArray();
    
    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    

提交回复
热议问题