【问题标题】:crypto/sha1 not matching openssl commandcrypto/sha1 不匹配 openssl 命令
【发布时间】:2015-02-21 21:51:43
【问题描述】:

我正在尝试计算 sha1,但 sha1 与 openssl 命令不匹配。

我在我的 Macbook 上计算一个空文件的哈希值:

$ touch test.txt
$ openssl sha1 -hex test.txt
SHA1(test.txt)= da39a3ee5e6b4b0d3255bfef95601890afd80709

here 是我的简单测试代码:

package main

import "fmt"
import "crypto/sha1"

func main() {
        hash := sha1.New()
        hash.Write([]byte{0x00})
        fmt.Printf("Hash got %x, expected da39a3ee5e6b4b0d3255bfef95601890afd80709", hash.Sum(nil))
}

这是你看到的输出不匹配的输出,有人知道我做错了什么吗?

Hash got 5ba93c9db0cff93f52b521d7420e43f6eda2784f, expected da39a3ee5e6b4b0d3255bfef95601890afd80709

【问题讨论】:

  • 在什么时候将test.txt 内容提供给sha1?你不是只计算0字节的sha1吗?
  • 对不起 - 你说 test.txt 是空的。但空可能与单字节 0 内容不同。

标签: go openssl sha


【解决方案1】:

您的 Go 代码正在计算长度为 1 的输入的 SHA,其值为 [ 0 ]

touch 命令实际上创建了一个空文件(零长度),因此等效的 Go 代码为:

hash := sha1.New()
// hash.Write([]byte{}) 
data := hash.Sum(nil)
fmt.Printf("hash: %x", data)

上面的(注释的)Write 调用是无操作的。 Playground

您的测试代码实际上似乎并未从文件中读取。无论如何,根据您的要求,这是一个完整的 sha 实用程序在 Go 中的样子:

package main

import (
        "crypto/sha1"
        "fmt"
        "io"
        "log"
        "os"
)

func main() {
        if len(os.Args) < 2 {
                fmt.Printf("usage: %s <file>\n", os.Args[0])
                os.Exit(1)
        }

        file := os.Args[1]

        f, err := os.Open(file)

        if err != nil {
                log.Fatal(err)
        }

        defer f.Close()

        hash := sha1.New()

        _, err = io.Copy(hash, f)

        if err != nil {
                log.Fatal(err)
        }

        fmt.Printf("%x\n", hash.Sum(nil))
}

测试一下,我得到:

$ touch test.txt
$ go run sha.go test.txt
da39a3ee5e6b4b0d3255bfef95601890afd80709

【讨论】:

  • 是的,这似乎适用于 0 长度输入。在我的代码中,我实际上是从文件中读取并直接写入哈希,但它不匹配。您能否提供一个从与 openssl 命令匹配的文件中读取的示例?
  • 感谢您的示例,我的问题源于另一个包。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-10
相关资源
最近更新 更多