-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.go
56 lines (44 loc) · 1.35 KB
/
example.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// This example was lifted from https://pkg.go.dev/golang.org/x/[email protected]/chacha20poly1305#example-NewX
package main
import (
"crypto/rand"
"fmt"
"golang.org/x/crypto/chacha20poly1305"
)
func main() {
// key should be randomly generated or derived from a function like Argon2.
key := make([]byte, chacha20poly1305.KeySize)
if _, err := rand.Read(key); err != nil {
panic(err)
}
aead, err := chacha20poly1305.NewX(key)
if err != nil {
panic(err)
}
// Encryption.
var encryptedMsg []byte
{
msg := []byte("Gophers, gophers, gophers everywhere!")
// Select a random nonce, and leave capacity for the ciphertext.
nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(msg)+aead.Overhead())
if _, err := rand.Read(nonce); err != nil {
panic(err)
}
// Encrypt the message and append the ciphertext to the nonce.
encryptedMsg = aead.Seal(nonce, nonce, msg, nil) // want "Seal is not a FIPS-validated implementation"
}
// Decryption.
{
if len(encryptedMsg) < aead.NonceSize() {
panic("ciphertext too short")
}
// Split nonce and ciphertext.
nonce, ciphertext := encryptedMsg[:aead.NonceSize()], encryptedMsg[aead.NonceSize():]
// Decrypt the message and check it wasn't tampered with.
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", plaintext)
}
}