简体   繁体   中英

Calculating HMAC in JavaScript : converting from Java

I have a encryption function in Java that I am trying to convert to Javascript and for some reason the hash generated in the end is not the same.

I am using crypto for javascript and Mac for Java.

Javascript :

    const time = 0,0,0,0,0,8,21,60;
    const signKey = 20,54,50,82;

    const hash = crypto
       .createHmac('sha1', new Buffer(signKey, 'base64'))
       .update(new Buffer(time))
       .digest('hex');

    console.log(`hash ${hash}`);

Java :

    byte[] time = 0,0,0,0,0,8,21,60;
    byte[] signKey = 20,54,50,82;
     SecretKeySpec signKey = new SecretKeySpec(signKey, "HmacSHA1");

    Mac mac;
    mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(time);

Javascript - Output :

hash = 52,56,48

Java - Output : hash = [-47, 30, -1]

I think I am missing to convert something in Javascript, but as I am not familiar with cryptos, I am not sure.

Thank you !

As I can see in JS you are treating signKey as base64 encoded string and in Java -- as byte array. So removing 'base64' from JS code should help.

Hi I managed to find the solution, so yes indeed one of the things was remove the base64 and the Buffers from the JS code and also I should digest without converting it to hexadecimal.

Sincer I removed the Buffer, I had to convert both of the Arrays into TypedArrays since crypto just accepts, Buffers, TypedArrays, String and DataViews.

After this I should convert the hash into a Unit32Array and this should be the same hash from the Java code

So, in the end the code is:

         const timeInBytes = 0,0,0,0,0,8,21,60;
         const combinedSecret = 20,54,50,82;

         const signKey = Uint8Array.from(combinedSecret);
         const time = Uint8Array.from(timeInBytes);

         const hash = crypto
            .createHmac('sha1', signKey)
            .update(time)
            .digest();

        const encodedArray = Uint32Array.from(hash);

Thank you guys !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM