Question

I have a method which is generating HMAC value from public and private key.

Here is my method code:

String mykey = "fb6a1271f98099ac96cc0002d5e8022b";
String test = "json6b17f33e25e2d8197462d1c6bcb0b1302156641988";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),
            "HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(test.getBytes());
    for (byte b : digest) {
        System.out.format("%02x", b);        
    }

    System.out.println();
} catch (Exception e) {
    System.out.println(e.getMessage());
}

Now as per requirement, I need to use the value returned from it as String.

Here is the value returned from method in

System.out.format("%02x", b); =bd0aea241e88c8a22692eba02887ad97a220f827 

Please help me..

Was it helpful?

Solution

I would recommend something like this (use a StringBuilder)

    StringBuilder sb = new StringBuilder(digest.length * 2);  

    Formatter formatter = new Formatter(sb);  
    for (byte b : digest) {  
        formatter.format("%02x", b);  
    }  

    return sb.toString();  

OTHER TIPS

BigInteger has excellent base conversion facilities if you are looking for the HEX form of the string:

return new BigInteger(mac.doFinal(test.getBytes())).toString(16);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top