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