如何在Java的Hash顶部执行base64

发布于 2025-01-31 04:38:07 字数 607 浏览 2 评论 0 原文

我在JavaScript中有以下示例,我似乎找不到Java中的等效物

var rapyd_signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(data, key));
rapyd_signature = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(rapyd_signature));

(我所拥有的东西都没有给出相同的结果)

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);
byte[] tobeEncoded =  data.getBytes(StandardCharsets.UTF_8);
String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);

I have the following example in Javascript, I can't seem to find the equivalent in Java for it

var rapyd_signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(data, key));
rapyd_signature = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(rapyd_signature));

What I have (which does not give the same result)

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);
byte[] tobeEncoded =  data.getBytes(StandardCharsets.UTF_8);
String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墟烟 2025-02-07 04:38:07

您初始化的 hmacsha256 …然后您没有对此做任何事情。

您需要通过调用 hmacsha256.dofinal 来实际哈希数据。

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);

byte[] tobeEncoded = data.getBytes(StandardCharsets.UTF_8);
toBeEncoded = hmacSHA256.doFinal(toBeEncoded);

String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);

You initialized hmacSHA256 … and then you didn’t do anything with it.

You need to actually hash the data, by calling hmacSHA256.doFinal:

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);

byte[] tobeEncoded = data.getBytes(StandardCharsets.UTF_8);
toBeEncoded = hmacSHA256.doFinal(toBeEncoded);

String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文