secretbox_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2012 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 secretbox
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "encoding/hex"
  9. "testing"
  10. )
  11. func TestSealOpen(t *testing.T) {
  12. var key [32]byte
  13. var nonce [24]byte
  14. rand.Reader.Read(key[:])
  15. rand.Reader.Read(nonce[:])
  16. var box, opened []byte
  17. for msgLen := 0; msgLen < 128; msgLen += 17 {
  18. message := make([]byte, msgLen)
  19. rand.Reader.Read(message)
  20. box = Seal(box[:0], message, &nonce, &key)
  21. var ok bool
  22. opened, ok = Open(opened[:0], box, &nonce, &key)
  23. if !ok {
  24. t.Errorf("%d: failed to open box", msgLen)
  25. continue
  26. }
  27. if !bytes.Equal(opened, message) {
  28. t.Errorf("%d: got %x, expected %x", msgLen, opened, message)
  29. continue
  30. }
  31. }
  32. for i := range box {
  33. box[i] ^= 0x20
  34. _, ok := Open(opened[:0], box, &nonce, &key)
  35. if ok {
  36. t.Errorf("box was opened after corrupting byte %d", i)
  37. }
  38. box[i] ^= 0x20
  39. }
  40. }
  41. func TestSecretBox(t *testing.T) {
  42. var key [32]byte
  43. var nonce [24]byte
  44. var message [64]byte
  45. for i := range key[:] {
  46. key[i] = 1
  47. }
  48. for i := range nonce[:] {
  49. nonce[i] = 2
  50. }
  51. for i := range message[:] {
  52. message[i] = 3
  53. }
  54. box := Seal(nil, message[:], &nonce, &key)
  55. // expected was generated using the C implementation of NaCl.
  56. expected, _ := hex.DecodeString("8442bc313f4626f1359e3b50122b6ce6fe66ddfe7d39d14e637eb4fd5b45beadab55198df6ab5368439792a23c87db70acb6156dc5ef957ac04f6276cf6093b84be77ff0849cc33e34b7254d5a8f65ad")
  57. if !bytes.Equal(box, expected) {
  58. t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected)
  59. }
  60. }
  61. func TestAppend(t *testing.T) {
  62. var key [32]byte
  63. var nonce [24]byte
  64. var message [8]byte
  65. out := make([]byte, 4)
  66. box := Seal(out, message[:], &nonce, &key)
  67. if !bytes.Equal(box[:4], out[:4]) {
  68. t.Fatalf("Seal didn't correctly append")
  69. }
  70. out = make([]byte, 4, 100)
  71. box = Seal(out, message[:], &nonce, &key)
  72. if !bytes.Equal(box[:4], out[:4]) {
  73. t.Fatalf("Seal didn't correctly append with sufficient capacity.")
  74. }
  75. }