sha3_test.go 9.7 KB

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