Go 加密/sha1与openssl命令不匹配

Go 加密/sha1与openssl命令不匹配,go,openssl,sha,Go,Openssl,Sha,我试图计算sha1,但sha1与openssl命令不匹配 我在Macbook上计算空文件的哈希值,如下所示: $ touch test.txt $ openssl sha1 -hex test.txt SHA1(test.txt)= da39a3ee5e6b4b0d3255bfef95601890afd80709 这是我的简单测试代码: package main import "fmt" import "crypto/sha1" func main() { hash :=

我试图计算sha1,但sha1与openssl命令不匹配

我在Macbook上计算空文件的哈希值,如下所示:

$ touch test.txt
$ openssl sha1 -hex test.txt
SHA1(test.txt)= da39a3ee5e6b4b0d3255bfef95601890afd80709
这是我的简单测试代码:

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

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

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

hash := sha1.New()
// hash.Write([]byte{}) 
data := hash.Sum(nil)
fmt.Printf("hash: %x", data)
上面的(注释)写调用是不可操作的

您的测试代码实际上似乎不是从文件中读取的。无论如何,根据您的请求,以下是Go中完整sha实用程序的外观:

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))
}

您在什么时候向sha1提供
test.txt
内容?你不是只计算0字节的sha1吗?对不起-你说test.txt是空的。但是空可能不同于单字节0内容。是的,这似乎适用于长度为0的输入。在我的代码中,我实际上是从一个文件中读取并直接写入哈希,但它不匹配。您能提供一个从与openssl命令匹配的文件读取的示例吗?感谢您的示例,我的问题源于另一个包。
$ touch test.txt
$ go run sha.go test.txt
da39a3ee5e6b4b0d3255bfef95601890afd80709