You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

311 lines
8.9 KiB

  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sha3
  5. // Tests include all the ShortMsgKATs provided by the Keccak team at
  6. // https://github.com/gvanas/KeccakCodePackage
  7. //
  8. // They only include the zero-bit case of the bitwise testvectors
  9. // published by NIST in the draft of FIPS-202.
  10. import (
  11. "bytes"
  12. "compress/flate"
  13. "encoding/hex"
  14. "encoding/json"
  15. "fmt"
  16. "hash"
  17. "os"
  18. "strings"
  19. "testing"
  20. )
  21. const (
  22. testString = "brekeccakkeccak koax koax"
  23. katFilename = "testdata/keccakKats.json.deflate"
  24. )
  25. // Internal-use instances of SHAKE used to test against KATs.
  26. func newHashShake128() hash.Hash {
  27. return &state{rate: 168, dsbyte: 0x1f, outputLen: 512}
  28. }
  29. func newHashShake256() hash.Hash {
  30. return &state{rate: 136, dsbyte: 0x1f, outputLen: 512}
  31. }
  32. // testDigests contains functions returning hash.Hash instances
  33. // with output-length equal to the KAT length for both SHA-3 and
  34. // SHAKE instances.
  35. var testDigests = map[string]func() hash.Hash{
  36. "SHA3-224": New224,
  37. "SHA3-256": New256,
  38. "SHA3-384": New384,
  39. "SHA3-512": New512,
  40. "SHAKE128": newHashShake128,
  41. "SHAKE256": newHashShake256,
  42. }
  43. // testShakes contains functions that return ShakeHash instances for
  44. // testing the ShakeHash-specific interface.
  45. var testShakes = map[string]func() ShakeHash{
  46. "SHAKE128": NewShake128,
  47. "SHAKE256": NewShake256,
  48. }
  49. // decodeHex converts a hex-encoded string into a raw byte string.
  50. func decodeHex(s string) []byte {
  51. b, err := hex.DecodeString(s)
  52. if err != nil {
  53. panic(err)
  54. }
  55. return b
  56. }
  57. // structs used to marshal JSON test-cases.
  58. type KeccakKats struct {
  59. Kats map[string][]struct {
  60. Digest string `json:"digest"`
  61. Length int64 `json:"length"`
  62. Message string `json:"message"`
  63. }
  64. }
  65. func testUnalignedAndGeneric(t *testing.T, testf func(impl string)) {
  66. xorInOrig, copyOutOrig := xorIn, copyOut
  67. xorIn, copyOut = xorInGeneric, copyOutGeneric
  68. testf("generic")
  69. if xorImplementationUnaligned != "generic" {
  70. xorIn, copyOut = xorInUnaligned, copyOutUnaligned
  71. testf("unaligned")
  72. }
  73. xorIn, copyOut = xorInOrig, copyOutOrig
  74. }
  75. // TestKeccakKats tests the SHA-3 and Shake implementations against all the
  76. // ShortMsgKATs from https://github.com/gvanas/KeccakCodePackage
  77. // (The testvectors are stored in keccakKats.json.deflate due to their length.)
  78. func TestKeccakKats(t *testing.T) {
  79. testUnalignedAndGeneric(t, func(impl string) {
  80. // Read the KATs.
  81. deflated, err := os.Open(katFilename)
  82. if err != nil {
  83. t.Errorf("error opening %s: %s", katFilename, err)
  84. }
  85. file := flate.NewReader(deflated)
  86. dec := json.NewDecoder(file)
  87. var katSet KeccakKats
  88. err = dec.Decode(&katSet)
  89. if err != nil {
  90. t.Errorf("error decoding KATs: %s", err)
  91. }
  92. // Do the KATs.
  93. for functionName, kats := range katSet.Kats {
  94. d := testDigests[functionName]()
  95. for _, kat := range kats {
  96. d.Reset()
  97. in, err := hex.DecodeString(kat.Message)
  98. if err != nil {
  99. t.Errorf("error decoding KAT: %s", err)
  100. }
  101. d.Write(in[:kat.Length/8])
  102. got := strings.ToUpper(hex.EncodeToString(d.Sum(nil)))
  103. if got != kat.Digest {
  104. t.Errorf("function=%s, implementation=%s, length=%d\nmessage:\n %s\ngot:\n %s\nwanted:\n %s",
  105. functionName, impl, kat.Length, kat.Message, got, kat.Digest)
  106. t.Logf("wanted %+v", kat)
  107. t.FailNow()
  108. }
  109. continue
  110. }
  111. }
  112. })
  113. }
  114. // TestUnalignedWrite tests that writing data in an arbitrary pattern with
  115. // small input buffers.
  116. func testUnalignedWrite(t *testing.T) {
  117. testUnalignedAndGeneric(t, func(impl string) {
  118. buf := sequentialBytes(0x10000)
  119. for alg, df := range testDigests {
  120. d := df()
  121. d.Reset()
  122. d.Write(buf)
  123. want := d.Sum(nil)
  124. d.Reset()
  125. for i := 0; i < len(buf); {
  126. // Cycle through offsets which make a 137 byte sequence.
  127. // Because 137 is prime this sequence should exercise all corner cases.
  128. offsets := [17]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 1}
  129. for _, j := range offsets {
  130. if v := len(buf) - i; v < j {
  131. j = v
  132. }
  133. d.Write(buf[i : i+j])
  134. i += j
  135. }
  136. }
  137. got := d.Sum(nil)
  138. if !bytes.Equal(got, want) {
  139. t.Errorf("Unaligned writes, implementation=%s, alg=%s\ngot %q, want %q", impl, alg, got, want)
  140. }
  141. }
  142. })
  143. }
  144. // TestAppend checks that appending works when reallocation is necessary.
  145. func TestAppend(t *testing.T) {
  146. testUnalignedAndGeneric(t, func(impl string) {
  147. d := New224()
  148. for capacity := 2; capacity <= 66; capacity += 64 {
  149. // The first time around the loop, Sum will have to reallocate.
  150. // The second time, it will not.
  151. buf := make([]byte, 2, capacity)
  152. d.Reset()
  153. d.Write([]byte{0xcc})
  154. buf = d.Sum(buf)
  155. expected := "0000DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39"
  156. if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected {
  157. t.Errorf("got %s, want %s", got, expected)
  158. }
  159. }
  160. })
  161. }
  162. // TestAppendNoRealloc tests that appending works when no reallocation is necessary.
  163. func TestAppendNoRealloc(t *testing.T) {
  164. testUnalignedAndGeneric(t, func(impl string) {
  165. buf := make([]byte, 1, 200)
  166. d := New224()
  167. d.Write([]byte{0xcc})
  168. buf = d.Sum(buf)
  169. expected := "00DF70ADC49B2E76EEE3A6931B93FA41841C3AF2CDF5B32A18B5478C39"
  170. if got := strings.ToUpper(hex.EncodeToString(buf)); got != expected {
  171. t.Errorf("%s: got %s, want %s", impl, got, expected)
  172. }
  173. })
  174. }
  175. // TestSqueezing checks that squeezing the full output a single time produces
  176. // the same output as repeatedly squeezing the instance.
  177. func TestSqueezing(t *testing.T) {
  178. testUnalignedAndGeneric(t, func(impl string) {
  179. for functionName, newShakeHash := range testShakes {
  180. d0 := newShakeHash()
  181. d0.Write([]byte(testString))
  182. ref := make([]byte, 32)
  183. d0.Read(ref)
  184. d1 := newShakeHash()
  185. d1.Write([]byte(testString))
  186. var multiple []byte
  187. for range ref {
  188. one := make([]byte, 1)
  189. d1.Read(one)
  190. multiple = append(multiple, one...)
  191. }
  192. if !bytes.Equal(ref, multiple) {
  193. t.Errorf("%s (%s): squeezing %d bytes one at a time failed", functionName, impl, len(ref))
  194. }
  195. }
  196. })
  197. }
  198. // sequentialBytes produces a buffer of size consecutive bytes 0x00, 0x01, ..., used for testing.
  199. func sequentialBytes(size int) []byte {
  200. result := make([]byte, size)
  201. for i := range result {
  202. result[i] = byte(i)
  203. }
  204. return result
  205. }
  206. // BenchmarkPermutationFunction measures the speed of the permutation function
  207. // with no input data.
  208. func BenchmarkPermutationFunction(b *testing.B) {
  209. b.SetBytes(int64(200))
  210. var lanes [25]uint64
  211. for i := 0; i < b.N; i++ {
  212. keccakF1600(&lanes)
  213. }
  214. }
  215. // benchmarkHash tests the speed to hash num buffers of buflen each.
  216. func benchmarkHash(b *testing.B, h hash.Hash, size, num int) {
  217. b.StopTimer()
  218. h.Reset()
  219. data := sequentialBytes(size)
  220. b.SetBytes(int64(size * num))
  221. b.StartTimer()
  222. var state []byte
  223. for i := 0; i < b.N; i++ {
  224. for j := 0; j < num; j++ {
  225. h.Write(data)
  226. }
  227. state = h.Sum(state[:0])
  228. }
  229. b.StopTimer()
  230. h.Reset()
  231. }
  232. // benchmarkShake is specialized to the Shake instances, which don't
  233. // require a copy on reading output.
  234. func benchmarkShake(b *testing.B, h ShakeHash, size, num int) {
  235. b.StopTimer()
  236. h.Reset()
  237. data := sequentialBytes(size)
  238. d := make([]byte, 32)
  239. b.SetBytes(int64(size * num))
  240. b.StartTimer()
  241. for i := 0; i < b.N; i++ {
  242. h.Reset()
  243. for j := 0; j < num; j++ {
  244. h.Write(data)
  245. }
  246. h.Read(d)
  247. }
  248. }
  249. func BenchmarkSha3_512_MTU(b *testing.B) { benchmarkHash(b, New512(), 1350, 1) }
  250. func BenchmarkSha3_384_MTU(b *testing.B) { benchmarkHash(b, New384(), 1350, 1) }
  251. func BenchmarkSha3_256_MTU(b *testing.B) { benchmarkHash(b, New256(), 1350, 1) }
  252. func BenchmarkSha3_224_MTU(b *testing.B) { benchmarkHash(b, New224(), 1350, 1) }
  253. func BenchmarkShake128_MTU(b *testing.B) { benchmarkShake(b, NewShake128(), 1350, 1) }
  254. func BenchmarkShake256_MTU(b *testing.B) { benchmarkShake(b, NewShake256(), 1350, 1) }
  255. func BenchmarkShake256_16x(b *testing.B) { benchmarkShake(b, NewShake256(), 16, 1024) }
  256. func BenchmarkShake256_1MiB(b *testing.B) { benchmarkShake(b, NewShake256(), 1024, 1024) }
  257. func BenchmarkSha3_512_1MiB(b *testing.B) { benchmarkHash(b, New512(), 1024, 1024) }
  258. func Example_sum() {
  259. buf := []byte("some data to hash")
  260. // A hash needs to be 64 bytes long to have 256-bit collision resistance.
  261. h := make([]byte, 64)
  262. // Compute a 64-byte hash of buf and put it in h.
  263. ShakeSum256(h, buf)
  264. fmt.Printf("%x\n", h)
  265. // Output: 0f65fe41fc353e52c55667bb9e2b27bfcc8476f2c413e9437d272ee3194a4e3146d05ec04a25d16b8f577c19b82d16b1424c3e022e783d2b4da98de3658d363d
  266. }
  267. func Example_mac() {
  268. k := []byte("this is a secret key; you should generate a strong random key that's at least 32 bytes long")
  269. buf := []byte("and this is some data to authenticate")
  270. // A MAC with 32 bytes of output has 256-bit security strength -- if you use at least a 32-byte-long key.
  271. h := make([]byte, 32)
  272. d := NewShake256()
  273. // Write the key into the hash.
  274. d.Write(k)
  275. // Now write the data.
  276. d.Write(buf)
  277. // Read 32 bytes of output from the hash into h.
  278. d.Read(h)
  279. fmt.Printf("%x\n", h)
  280. // Output: 78de2974bd2711d5549ffd32b753ef0f5fa80a0db2556db60f0987eb8a9218ff
  281. }