2014-12-23 73 views
1

我正在嘗試計算sha1,但是sha1與openssl命令不匹配。crypto/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 
+0

在哪一點你喂'test.txt'內容到sha1?你不計算0字節的sha1嗎? –

+1

對不起 - 你說test.txt是空的。但空單元可能與單字節0內容不同。 –

回答

5

你Go代碼被計算SHA長度1的輸入的,具有[ 0 ]的值。

touch命令實際創建一個空文件(零長度),所以等效Go代碼將是:

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

的(評論)收件撥打以上是無操作。 Playground

您的測試代碼實際上並不是從文件中讀取的。總之,按照您的要求,這裏是一個完整的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)) 
} 

測試出來,我得到:

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

是的,這似乎適用於0長度輸入。在我的代碼中,我實際上是從文件中讀取並直接寫入散列並且它不匹配。你能提供一個與openssl命令相匹配的文件讀取的例子嗎? –

+0

感謝你的例子,我的問題源於另一個包。 –