...
1 package box_test
2
3 import (
4 crypto_rand "crypto/rand"
5 "fmt"
6 "io"
7
8 "golang.org/x/crypto/nacl/box"
9 )
10
11 func Example() {
12 senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
13 if err != nil {
14 panic(err)
15 }
16
17 recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
18 if err != nil {
19 panic(err)
20 }
21
22
23
24
25 var nonce [24]byte
26 if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
27 panic(err)
28 }
29
30 msg := []byte("Alas, poor Yorick! I knew him, Horatio")
31
32 encrypted := box.Seal(nonce[:], msg, &nonce, recipientPublicKey, senderPrivateKey)
33
34
35
36
37
38
39 var decryptNonce [24]byte
40 copy(decryptNonce[:], encrypted[:24])
41 decrypted, ok := box.Open(nil, encrypted[24:], &decryptNonce, senderPublicKey, recipientPrivateKey)
42 if !ok {
43 panic("decryption error")
44 }
45 fmt.Println(string(decrypted))
46
47 }
48
49 func Example_precompute() {
50 senderPublicKey, senderPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
51 if err != nil {
52 panic(err)
53 }
54
55 recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(crypto_rand.Reader)
56 if err != nil {
57 panic(err)
58 }
59
60
61
62 sharedEncryptKey := new([32]byte)
63 box.Precompute(sharedEncryptKey, recipientPublicKey, senderPrivateKey)
64
65
66
67
68 var nonce [24]byte
69 if _, err := io.ReadFull(crypto_rand.Reader, nonce[:]); err != nil {
70 panic(err)
71 }
72
73 msg := []byte("A fellow of infinite jest, of most excellent fancy")
74
75 encrypted := box.SealAfterPrecomputation(nonce[:], msg, &nonce, sharedEncryptKey)
76
77
78
79 var sharedDecryptKey [32]byte
80 box.Precompute(&sharedDecryptKey, senderPublicKey, recipientPrivateKey)
81
82
83
84
85
86
87 var decryptNonce [24]byte
88 copy(decryptNonce[:], encrypted[:24])
89 decrypted, ok := box.OpenAfterPrecomputation(nil, encrypted[24:], &decryptNonce, &sharedDecryptKey)
90 if !ok {
91 panic("decryption error")
92 }
93 fmt.Println(string(decrypted))
94
95 }
96
View as plain text