dongyou26216708 2015-05-15 06:37
浏览 639
已采纳

Go Hmac SHA1生成的哈希与Java中的Hmac SHA1不同

I'm just starting to learn Go and I'm trying to rewrite my existing small application from Java to Go.

I need to create Base64 hash of input string with key using Hmac SHA1 algorithm.

My Java code:

private String getSignedBody(String input, String key) {
    String result = "";
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(input.getBytes("UTF-8"));
        result = Base64.encodeToString(rawHmac, false);
    } catch (Exception e) {
        Logger.error("Failed to generate signature: " + e.getMessage());
    }
    return result;
}

My Go code:

func GetSignature(input, key string) string {
    key_for_sign := []byte(key)
    h := hmac.New(sha1.New, key_for_sign)
    h.Write([]byte(input))
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

The problem is that Go code generates output that is not expected. For example, for input string "qwerty" and key "key" Java output will be RiD1vimxoaouU3VB1sVmchwhfhg= and Go output will be 9Cuw7rAY671Fl65yE3EexgdghD8=.

Where did I make mistakes in the Go code?

  • 写回答

1条回答 默认 最新

  • dtdt0454 2015-05-15 07:02
    关注

    The Go code you provided gives exactly the same output as the Java code.

    Try it on the Go Playground.

    Output:

    RiD1vimxoaouU3VB1sVmchwhfhg=
    

    You made the mistake when you called your GetSignature() function. Call it like the linked example code:

    fmt.Println(GetSignature("qwerty", "key"))
    

    Your mistake was that you passed an empty input to your GetSignature() function. Calling it with empty "" input and "key" key produces the non-expected output you provided:

    fmt.Println(GetSignature("", "key"))
    

    Output:

    9Cuw7rAY671Fl65yE3EexgdghD8=
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路
  • ¥15 内网办公电脑进行向日葵
  • ¥15 如何输入双曲线的参数a然后画出双曲线?我输入处理函数加上后就没有用了,不知道怎么回事去掉后双曲线可以画出来
  • ¥15 soildworks装配体的尺寸问题
  • ¥100 有偿寻云闪付SDK转URL技术