HMAC SHA1 Signature in Java

前端 未结 2 1439
失恋的感觉
失恋的感觉 2021-01-13 05:13

I am trying to interface with a TransUnion web service and I need to provide a HMAC-SHA1 signature to access it.

This example is in the TransUnion documentation:

相关标签:
2条回答
  • 2021-01-13 05:47

    That looks like a Base64 encoded key. So I think you're going to need to do a base64 decode on it, then pass it to the HMAC. Something like this (just for illustration I haven't tested it, any errors are an exercise for the reader):

    public String getHmacMD5(String privateKey, String input) throws Exception{
        String algorithm = "HmacSHA1";
        byte[] keyBytes = Base64.decode(privateKey);
        Key key = new SecretKeySpec(keyBytes, 0, keyBytes.length, algorithm); 
        Mac mac = Mac.getInstance(algorithm);
        mac.init(key); 
        return Base64.encode(mac.doFinal(input.getBytes()));
    }
    
    0 讨论(0)
  • 2021-01-13 06:00

    One thing I noticed is that the hyphens are not normal hyphens. If you copy and paste them, they are not in the ASCII character set. All I can say for sure is that the hash length appears correct. The funny thing is, I couldn't get your code to produce the correct answer, even after putting the correct hyphens in. But no matter. It solved the problem. Huzzah!

    0 讨论(0)
提交回复
热议问题