· 9 years ago · Oct 31, 2016, 12:06 AM
1package main
2
3import (
4 "fmt"
5 "os"
6
7 "crypto/rand"
8 "golang.org/x/crypto/nacl/secretbox"
9)
10
11func generateRandomBytes(n int) []byte {
12 b := make([]byte, n)
13 _, err := rand.Read(b)
14 if err != nil {
15 fmt.Println(err)
16 os.Exit(1)
17 }
18 return b
19}
20
21func encrypt(plaintext, key []byte) []byte {
22 nonceSlice := generateRandomBytes(24)
23
24 var nonce [24]byte
25 copy(nonce[:], nonceSlice)
26
27 var secretKey [32]byte
28 copy(secretKey[:], key)
29
30 return secretbox.Seal(nonce[:], plaintext, &nonce, &secretKey)
31}
32
33func decrypt(ciphertext, key []byte) []byte {
34 var nonce [24]byte
35 copy(nonce[:], ciphertext[:24])
36
37 var secretKey [32]byte
38 copy(secretKey[:], key)
39
40 plaintext, okay := secretbox.Open([]byte{}, ciphertext[24:], &nonce, &secretKey)
41 if !okay {
42 fmt.Println("decryption failed")
43 os.Exit(1)
44 }
45
46 return plaintext
47}
48
49func main() {
50 key := generateRandomBytes(32)
51
52 plaintext := "toby doesn't appreciate being called mean words"
53 fmt.Println(plaintext)
54
55 ciphertext := encrypt([]byte(plaintext), key)
56 fmt.Println(ciphertext)
57
58 plaintext = string(decrypt(ciphertext, key))
59 fmt.Println(plaintext)
60}