[英]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. 我在Java中有一个加密功能,试图将其转换为Javascript,由于某种原因,最终生成的哈希值不相同。
I am using crypto for javascript and Mac for Java. 我正在为Javascript使用加密货币,为Java而使用Mac。
Javascript : 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 : 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 : Javascript-输出 :
hash = 52,56,48
Java - Output : hash = [-47, 30, -1]
Java-输出 : 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. 我想我缺少在Javascript中进行某些转换的方法,但是由于我不熟悉加密技术,因此我不确定。
Thank you ! 谢谢 !
As I can see in JS you are treating signKey as base64 encoded string and in Java -- as byte array. 正如我在JS中看到的那样,您将signKey视为base64编码的字符串,而在Java中则将其视为字节数组。 So removing 'base64' from JS code should help. 因此,从JS代码中删除'base64'应该会有所帮助。
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. 嗨,我设法找到了解决方案,所以是的,确实的一件事是从JS代码中删除了base64和Buffers,而且我应该摘要而不将其转换为十六进制。
Sincer I removed the Buffer, I had to convert both of the Arrays into TypedArrays since crypto just accepts, Buffers, TypedArrays, String and DataViews. 由于我删除了缓冲区,由于加密仅接受缓冲区,TypedArrays,String和DataViews,所以我不得不将两个数组都转换为TypedArrays。
After this I should convert the hash into a Unit32Array and this should be the same hash from the Java code 之后,我应该将哈希转换为Unit32Array,并且应该与Java代码中的哈希相同
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 ! 感谢大伙们 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.