Almost I got stuck in the js implementation of go lang hmac.New for several days. However, no success. I used crypto
,crypto-js
and stablelib
modules for implementation. The problem is that in go lang version, hmac
instance can be created by hmac
instance. For example (the code block is correct and tested):
hmacf := hmac.New(func() hash.Hash {
return hmac.New(func() hash.Hash {
return hmac.New(func() hash.Hash {
return hmac.New(sha256.New, []byte(SALT))
}, []byte(path[0]))
}, []byte(path[1]))
}, []byte(path[2]))
Actually, I don’t know how does it work! because in all javascript related modules, You can’t create hmac
from hmac
, and they accept an string
value that determines hashing algorithm.
maybe it’s better to ask how to create hmac
from hmac
in javascript.
What is the solution?
When the output of go version is the same with the output of your implementation; Your solution is correct.
2
Answers
Maybe you need something like this?
You may also like a solution like
WebAssembly
.According to the specification (RFC 2104), an HMAC uses a digest function internally, e.g. SHA256.
However, your implementation applies (actually non-compliant) HMACs that internally use another HMAC instead of a digest, where only the lowest level HMAC uses a regular digest internally. In this way, a nested structure is created.
Based on the specification of a regular HMAC (with a digest), this can be extended to the HMAC with an HMAC (instead of a digest) as used in the Go code:
HMAC(K XOR opad, HMAC(K XOR ipad, text))
s. RFC2104, sec 2. Definition of HMACBecause of the difference from the specification, it will probably not be so easy to find a JavaScript library that supports something like this out of the box.
Although most libraries of course support an HMAC, but only allow the specification of a digest (and not of an HMAC), e.g.
crypto.createHmac()
of the crypto module of NodeJS, see also the other answer. I don’t think this approach can be used to implement the logic from the Go code.If the approach of the other answer doesn’t work and you can’t find another JavaScript library with the needed functionality, you can implement the logic in JavaScript yourself, because the specification of the HMAC is relatively simple (s. above).
The following code is a sample implementation with the crypto module of NodeJS:
with the result:
Test:
The following Go code produces the same result: