Java Node.js Hmac SHA256 base64 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20004530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:16:49  来源:igfitidea点击:

Node.js Hmac SHA256 base64 of string

javaandroidnode.js

提问by just_user

I'm making an app in java and a server with node and as an authentication method I would like to compare two strings.

我正在用 Java 制作一个应用程序和一个带有节点的服务器,作为一种身份验证方法,我想比较两个字符串。

In java i'm doing this:

在java中我这样做:

try {
    String secret = "secret";
    String message = "Message";

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);

    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
    System.out.println(hash);
} catch (Exception e){
    System.out.println("Error");
}

But I'm still pretty new to node.js and I'm trying to figure out how to do the same there. This is what I've got:

但我对 node.js 还是很陌生,我正试图弄清楚如何在那里做同样的事情。这就是我所拥有的:

var crypto = require('crypto');
var sha256 = crypto.createHash('HMAC-SHA256').update('Message').digest("base64");

How can I make them do the same? I'm still missing the salt in node.js. Suggestions?

我怎样才能让他们做同样的事情?我仍然缺少 node.js 中的盐。建议?

EDIT:The answer below helped me find the solution. If other android users has this problem then this code worked for me:

编辑:下面的答案帮助我找到了解决方案。如果其他 android 用户有这个问题,那么这段代码对我有用:

try {
    String secret = "secret";
    String message = "Message";

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    byte[] s53 = sha256_HMAC.doFinal(message.getBytes());
    String hash = Base64.encodeToString(s53, Base64.DEFAULT);
    Log.e("beadict", hash);
} catch (Exception e){
    System.out.println("Error");
}

And this in node:

这在节点中:

var crypto = require('crypto');
var hash = crypto.createHmac('SHA256', "secret").update("Message").digest('base64');

采纳答案by Alex Netkachov

If you want to use a HMAC then you need to use the method crypto.createHmac(algorithm, key).

如果要使用 HMAC,则需要使用方法crypto.createHmac(algorithm, key)

I'm still missing the salt in node.js

我仍然缺少 node.js 中的盐

It seems that you do not use the salt in your Java code...

您似乎没有在 Java 代码中使用盐...

回答by your love

You can use this line:

您可以使用此行:

let test = crypto.createHmac('sha256', "key").update("json").digest("base64");

Convert to base64 last.

最后转换为 base64。