I'm converting code from Go to Java. The source to convert is at https://github.com/h2non/imaginary#url-signature and this is my current code converted to Java.
The problem is that I'm missing something, since the signature generated in Java is different than the one in Go.
Expected result (as in source in Go):
ruEWRoFO-ic-L38vTsjqIYE6DLZ532CTaZXOh1gwuVo
Actual result in Java:
x2clz4ynSxcFPNc6h3W832vyrIQ=
My code in Java:
@Test
public void testSomeString() throws Exception {
String signKey = "4f46feebafc4b5e988f131c4ff8b5997";
String urlPath = "/resize";
String urlQuery = "file=image.jpg&height=200&type=jpeg&width=300";
byte[] signKeyAsBytes = signKey.getBytes("UTF-8");
SecretKey SHA256_KEY = new SecretKeySpec(signKeyAsBytes, "HmacSHA256");
byte[] hashAsBytes=Hashing.hmacSha1(SHA256_KEY)
.newHasher()
.putString(urlPath, UTF_8)
.putString(urlQuery, UTF_8)
.hash().asBytes();
String hash = Base64.getUrlEncoder().encodeToString(hashAsBytes);
//correct value in GoLang is: "ruEWRoFO-ic-L38vTsjqIYE6DLZ532CTaZXOh1gwuVo"
Assert.assertEquals("ruEWRoFO-ic-L38vTsjqIYE6DLZ532CTaZXOh1gwuVo", hash);
/*
Junit test fails with:
Expected :ruEWRoFO-ic-L38vTsjqIYE6DLZ532CTaZXOh1gwuVo
Actual :x2clz4ynSxcFPNc6h3W832vyrIQ=
*/
}
And this is the original in Go:
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
)
func main() {
fmt.Println("Hello, playground")
signKey := "4f46feebafc4b5e988f131c4ff8b5997"
urlPath := "/resize"
urlQuery := "file=image.jpg&height=200&type=jpeg&width=300"
h := hmac.New(sha256.New, []byte(signKey))
h.Write([]byte(urlPath))
h.Write([]byte(urlQuery))
buf := h.Sum(nil)
fmt.Println("sign=" + base64.RawURLEncoding.EncodeToString(buf))
}