Generating HmacSHA256 signature in JUnit
Asked Answered
B

1

19

I'm trying to sign my message to Amazon AWS (inside JUnit test), but I encountered a problem. Here's the code I'm using:

String secretAccessKey = "secret1234678901";        
SecretKeySpec keySpec = new SecretKeySpec(secretAccessKey.getBytes(UTF-8), "HmacSHA256");
Mac mac = Mac.getInstance(this.MAC_ALGO);
mac.init(keySpec); // here it breaks
byte[] encoded = mac.doFinal(
    request.toString().getBytes(this.CHARSET));
return Base64.encodeBase64URLSafeString(encoded);

In the line marked (mac.init(...)) java throws exception:

java.lang.ClassCastException: com.sun.crypto.provider.HmacSHA1 cannot be cast to javax.crypto.MacSpi
    at javax.crypto.Mac.a(DashoA13*..)
    at javax.crypto.Mac.init(DashoA13*..)

Do you know why it happens? All the codes I've seen on the net look almost exactly like this, I also tried with HmacSHA1, with same results.

Bargeman answered 16/9, 2011 at 9:47 Comment(2)
That exception suggests that your Java configuration is very wrong. Are you perhaps mixing in your own version of jce.jar somewhere in the Java classpath? Modern Java already has all the crypto libraries built-in.Natala
Just a note: the code you posted does not compile, and if you make the changes to let it compile, it would never give this error message (you specify "HmacSHA256", but the error message says "HmacSHA1"). I suppose a configuration error, like Greg said, though.Mansoor
B
59

Sorry I didn't add everything. The code above was tested using junit and powermockito. But powermockito can't enhance javax.crypto classes so I had to add @PowerMockIgnore("javax.crypto.*") to the junit.

Bargeman answered 16/9, 2011 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.