box_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 box
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "encoding/hex"
  9. "testing"
  10. "golang.org/x/crypto/curve25519"
  11. )
  12. func TestSealOpen(t *testing.T) {
  13. publicKey1, privateKey1, _ := GenerateKey(rand.Reader)
  14. publicKey2, privateKey2, _ := GenerateKey(rand.Reader)
  15. if *privateKey1 == *privateKey2 {
  16. t.Fatalf("private keys are equal!")
  17. }
  18. if *publicKey1 == *publicKey2 {
  19. t.Fatalf("public keys are equal!")
  20. }
  21. message := []byte("test message")
  22. var nonce [24]byte
  23. box := Seal(nil, message, &nonce, publicKey1, privateKey2)
  24. opened, ok := Open(nil, box, &nonce, publicKey2, privateKey1)
  25. if !ok {
  26. t.Fatalf("failed to open box")
  27. }
  28. if !bytes.Equal(opened, message) {
  29. t.Fatalf("got %x, want %x", opened, message)
  30. }
  31. for i := range box {
  32. box[i] ^= 0x40
  33. _, ok := Open(nil, box, &nonce, publicKey2, privateKey1)
  34. if ok {
  35. t.Fatalf("opened box with byte %d corrupted", i)
  36. }
  37. box[i] ^= 0x40
  38. }
  39. }
  40. func TestBox(t *testing.T) {
  41. var privateKey1, privateKey2 [32]byte
  42. for i := range privateKey1[:] {
  43. privateKey1[i] = 1
  44. }
  45. for i := range privateKey2[:] {
  46. privateKey2[i] = 2
  47. }
  48. var publicKey1 [32]byte
  49. curve25519.ScalarBaseMult(&publicKey1, &privateKey1)
  50. var message [64]byte
  51. for i := range message[:] {
  52. message[i] = 3
  53. }
  54. var nonce [24]byte
  55. for i := range nonce[:] {
  56. nonce[i] = 4
  57. }
  58. box := Seal(nil, message[:], &nonce, &publicKey1, &privateKey2)
  59. // expected was generated using the C implementation of NaCl.
  60. expected, _ := hex.DecodeString("78ea30b19d2341ebbdba54180f821eec265cf86312549bea8a37652a8bb94f07b78a73ed1708085e6ddd0e943bbdeb8755079a37eb31d86163ce241164a47629c0539f330b4914cd135b3855bc2a2dfc")
  61. if !bytes.Equal(box, expected) {
  62. t.Fatalf("box didn't match, got\n%x\n, expected\n%x", box, expected)
  63. }
  64. }