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

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=
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效