// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // SHA256 hash algorithm. See FIPS 180-2. package sha256 import ( "bytes" "crypto/internal/boring" "crypto/internal/cryptotest" "encoding" "fmt" "hash" "internal/testenv" "io" "testing" ) type sha256Test struct { out string in string halfState string // marshaled hash state after first half of in written, used by TestGoldenMarshal } var golden = []sha256Test{ {"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "", "sha\x03j\t\xe6g\xbbg\xae\x85 0 { t.Errorf("allocs = %v, want 0", n) } } type cgoData struct { Data [16]byte Ptr *cgoData } func TestCgo(t *testing.T) { // Test that Write does not cause cgo to scan the entire cgoData struct for pointers. // The scan (if any) should be limited to the [16]byte. d := new(cgoData) d.Ptr = d _ = d.Ptr // for unusedwrite check h := New() h.Write(d.Data[:]) h.Sum(nil) } func TestHash(t *testing.T) { t.Run("SHA-224", func(t *testing.T) { cryptotest.TestAllImplementations(t, "crypto/sha256", func(t *testing.T) { cryptotest.TestHash(t, New224) }) }) t.Run("SHA-256", func(t *testing.T) { cryptotest.TestAllImplementations(t, "crypto/sha256", func(t *testing.T) { cryptotest.TestHash(t, New) }) }) } var bench = New() var buf = make([]byte, 8192) func benchmarkSize(b *testing.B, size int) { sum := make([]byte, bench.Size()) b.Run("New", func(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(size)) for i := 0; i < b.N; i++ { bench.Reset() bench.Write(buf[:size]) bench.Sum(sum[:0]) } }) b.Run("Sum224", func(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(size)) for i := 0; i < b.N; i++ { Sum224(buf[:size]) } }) b.Run("Sum256", func(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(size)) for i := 0; i < b.N; i++ { Sum256(buf[:size]) } }) } func BenchmarkHash8Bytes(b *testing.B) { benchmarkSize(b, 8) } func BenchmarkHash1K(b *testing.B) { benchmarkSize(b, 1024) } func BenchmarkHash8K(b *testing.B) { benchmarkSize(b, 8192) }