浏览代码

sha3: add NewLegacyKeccak256

Keccak uses a different domain separation byte as the NIST-
standardized SHA-3 hashing function.

Fixes golang/go#19709

Change-Id: I1b45afce9b7719241b24bbdc9b67718d73b457d3
GitHub-Last-Rev: 4f2a701c5ff0c6ee36c931794ea76bed9a98835e
GitHub-Pull-Request: golang/crypto#41
Reviewed-on: https://go-review.googlesource.com/106462
Run-TryBot: Filippo Valsorda <filippo@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Leon Klingele 7 年之前
父节点
当前提交
4ec37c66ab
共有 2 个文件被更改,包括 40 次插入8 次删除
  1. 6 0
      sha3/hashes.go
  2. 34 8
      sha3/sha3_test.go

+ 6 - 0
sha3/hashes.go

@@ -52,6 +52,12 @@ func New512() hash.Hash {
 	return &state{rate: 72, outputLen: 64, dsbyte: 0x06}
 }
 
+// NewLegacyKeccak256 creates a new Keccak-256 hash.
+//
+// Only use this function if you require compatibility with an existing cryptosystem
+// that uses non-standard padding. All other users should use New256 instead.
+func NewLegacyKeccak256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x01} }
+
 // Sum224 returns the SHA3-224 digest of the data.
 func Sum224(data []byte) (digest [28]byte) {
 	h := New224()

+ 34 - 8
sha3/sha3_test.go

@@ -36,15 +36,16 @@ func newHashShake256() hash.Hash {
 }
 
 // testDigests contains functions returning hash.Hash instances
-// with output-length equal to the KAT length for both SHA-3 and
-// SHAKE instances.
+// with output-length equal to the KAT length for SHA-3, Keccak
+// and SHAKE instances.
 var testDigests = map[string]func() hash.Hash{
-	"SHA3-224": New224,
-	"SHA3-256": New256,
-	"SHA3-384": New384,
-	"SHA3-512": New512,
-	"SHAKE128": newHashShake128,
-	"SHAKE256": newHashShake256,
+	"SHA3-224":   New224,
+	"SHA3-256":   New256,
+	"SHA3-384":   New384,
+	"SHA3-512":   New512,
+	"Keccak-256": NewLegacyKeccak256,
+	"SHAKE128":   newHashShake128,
+	"SHAKE256":   newHashShake256,
 }
 
 // testShakes contains functions that return ShakeHash instances for
@@ -124,6 +125,31 @@ func TestKeccakKats(t *testing.T) {
 	})
 }
 
+// TestKeccak does a basic test of the non-standardized Keccak hash functions.
+func TestKeccak(t *testing.T) {
+	tests := []struct {
+		fn   func() hash.Hash
+		data []byte
+		want string
+	}{
+		{
+			NewLegacyKeccak256,
+			[]byte("abc"),
+			"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45",
+		},
+	}
+
+	for _, u := range tests {
+		h := u.fn()
+		h.Write(u.data)
+		got := h.Sum(nil)
+		want := decodeHex(u.want)
+		if !bytes.Equal(got, want) {
+			t.Errorf("unexpected hash for size %d: got '%x' want '%s'", h.Size()*8, got, u.want)
+		}
+	}
+}
+
 // TestUnalignedWrite tests that writing data in an arbitrary pattern with
 // small input buffers.
 func TestUnalignedWrite(t *testing.T) {