-
-
Notifications
You must be signed in to change notification settings - Fork 452
/
aesgcm.go
executable file
·74 lines (59 loc) · 1.86 KB
/
aesgcm.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
// AesGcmEncrypt takes an encryption key and a plaintext string and encrypts it with AES256 in GCM mode, which provides authenticated encryption. Returns the ciphertext and the used nonce.
func AesGcmEncrypt(key []byte, plaintext string) (ciphertext, nonce []byte) {
plaintextBytes := []byte(plaintext)
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
nonce = make([]byte, 12)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
ciphertext = aesgcm.Seal(nil, nonce, plaintextBytes, nil)
fmt.Printf("Ciphertext: %x\n", ciphertext)
fmt.Printf("Nonce: %x\n", nonce)
return
}
// AesGcmDecrypt takes an decryption key, a ciphertext and the corresponding nonce and decrypts it with AES256 in GCM mode. Returns the plaintext string.
func AesGcmDecrypt(key, ciphertext, nonce []byte) (plaintext string) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintextBytes, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
plaintext = string(plaintextBytes)
fmt.Printf("%s\n", plaintext)
return
}
func main() {
// Generate an encryption key. 16 bytes = AES-128, 32 bytes = AES-256.
key := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, key); err != nil {
panic(err.Error())
}
// Specify the plaintext input
plaintext := "Lorem Ipsum"
ciphertext, nonce := AesGcmEncrypt(key, plaintext)
// For decryption you need to provide the nonce which was used for the encryption
plaintext = AesGcmDecrypt(key, ciphertext, nonce)
}