Files
2026-09-19 18:26:07 +03:00

71 lines
1.6 KiB
Go

package keccak
import (
"encoding/hex"
"testing"
)
func TestKeccak256KnownAnswers(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"empty", "", "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"},
{
"abc",
"abc",
"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45",
},
{
"longer",
"The quick brown fox jumps over the lazy dog",
"4d741b6f1eb29cb2a9b9911c82f56fa8d73b04959d3d9d222895df6c0b28aa15",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sum := Hash256([]byte(tc.in))
got := hex.EncodeToString(sum[:])
if got != tc.want {
t.Fatalf("Hash256(%q) = %s, want %s", tc.in, got, tc.want)
}
})
}
}
func TestStreamingMatchesOneShot(t *testing.T) {
data := make([]byte, 0, 500)
for i := 0; i < 500; i++ {
data = append(data, byte(i))
}
oneShot := Hash256(data)
h := New()
for i := 0; i < len(data); i += 7 {
end := i + 7
if end > len(data) {
end = len(data)
}
h.Write(data[i:end])
}
if got := h.Sum256(); got != oneShot {
t.Fatalf("streaming digest differs from one-shot")
}
}
// TestSum256DoesNotDisturbState ensures Sum256 clones the state (hash.Hash
// semantics) so repeated calls are stable.
func TestSum256DoesNotDisturbState(t *testing.T) {
h := New()
h.Write([]byte("abc"))
first := h.Sum256()
second := h.Sum256()
if first != second {
t.Fatalf("Sum256 mutated state")
}
if first != Hash256([]byte("abc")) {
t.Fatalf("Sum256 mismatch with Hash256")
}
}