Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating HmacSHA256 signature in JUnit

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.

like image 299
Krzysztof Krasoń Avatar asked Sep 16 '11 09:09

Krzysztof Krasoń


1 Answers

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.

like image 121
Krzysztof Krasoń Avatar answered Oct 06 '22 07:10

Krzysztof Krasoń