在 JUnit 中生成 HmacSHA256 签名
我正在尝试将消息签名到 Amazon AWS(在 JUnit 测试内),但遇到了问题。 这是我正在使用的代码:
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);
在标记为 (mac.init(...)
) 的行中,java 抛出异常:
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*..)
你知道为什么会发生吗?我在网上看到的所有代码看起来几乎都是这样,我也尝试过使用 HmacSHA1,结果相同。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抱歉我没有添加所有内容。上面的代码是使用 junit 和 powermockito 进行测试的。但 powermockito 无法增强 javax.crypto 类,因此我必须将
@PowerMockIgnore("javax.crypto.*")
添加到 junit。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.