diff --git a/lib/sha256/sha256.go b/lib/sha256/sha256.go index 46916757..51f489fb 100644 --- a/lib/sha256/sha256.go +++ b/lib/sha256/sha256.go @@ -9,6 +9,7 @@ package sha256 import ( "crypto/rand" cryptoSha256 "crypto/sha256" + "encoding/hex" "fmt" "hash" "os" @@ -66,6 +67,8 @@ func SelectAlgo() { // implementation as it may be disabled for incompatibility reasons. cryptoPerf = cpuBenchOnce(benchmarkingIterations*benchmarkingDuration, cryptoSha256.New) } + + verifyCorrectness() } // Report prints a line with the measured hash performance rates for the @@ -134,3 +137,24 @@ func formatRate(rate float64) string { } return fmt.Sprintf("%.*f MB/s", decimals, rate) } + +func verifyCorrectness() { + // The currently selected algo should in fact perform a SHA256 calculation. + + // $ echo "Syncthing Magic Testing Value" | openssl dgst -sha256 -hex + correct := "87f6cfd24131724c6ec43495594c5c22abc7d2b86bcc134bc6f10b7ec3dda4ee" + input := "Syncthing Magic Testing Value\n" + + h := New() + h.Write([]byte(input)) + sum := hex.EncodeToString(h.Sum(nil)) + if sum != correct { + panic("sha256 is broken") + } + + arr := Sum256([]byte(input)) + sum = hex.EncodeToString(arr[:]) + if sum != correct { + panic("sha256 is broken") + } +}