25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

79 lines
1.9 KiB

  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. }