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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同