Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Hmac SHA256 base64 of string

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

In java i'm doing this:

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:

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?

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

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'); 
like image 653
just_user Avatar asked Nov 15 '13 15:11

just_user


2 Answers

You can use this line:

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

Convert to base64 last.

like image 113
your love Avatar answered Sep 22 '22 13:09

your love


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

I'm still missing the salt in node.js

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

like image 43
Alex Netkachov Avatar answered Sep 24 '22 13:09

Alex Netkachov