-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-gcm.go
109 lines (82 loc) · 1.92 KB
/
api-gcm.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Golang presentation
*
* @package main
* @author @jeffotoni
* @size 2017
*/
package gcry
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
//"os"
)
func GenerateKey() (*[KeySize]byte, error) {
key := new([KeySize]byte)
_, err := io.ReadFull(rand.Reader, key[:])
if err != nil {
return nil, err
}
return key, nil
}
func GenerateNonce() (*[NonceSize]byte, error) {
nonce := new([NonceSize]byte)
_, err := io.ReadFull(rand.Reader, nonce[:])
if err != nil {
return nil, err
}
return nonce, nil
}
func EncryptGCM(text string) string {
// The key argument should be the AES key,
// either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte(KEY)
plaintext := []byte(text)
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err.Error())
}
// Never use more than 2^32 random nonces with a given key
// because of the risk of a repeat.
//Nonce, err := GenerateNonce()
Nonce = make([]byte, NonceSize)
if _, err := io.ReadFull(rand.Reader, Nonce); err != nil {
fmt.Println(err.Error())
}
//fmt.Println("nonce:", string(Nonce))
if err != nil {
fmt.Println(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
fmt.Println(err.Error())
}
ciphertext := aesgcm.Seal(nil, Nonce, plaintext, nil)
return fmt.Sprintf("%x", ciphertext)
}
func DecryptGCM(text string) string {
// The key argument should be the AES key, either 16 or 32 bytes
// to select AES-128 or AES-256.
key := []byte(KEY)
ciphertext, _ := hex.DecodeString(text)
nonce, _ := hex.DecodeString(fmt.Sprintf("%x", Nonce))
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err.Error())
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
fmt.Println(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
//panic(err.Error())
fmt.Println(err.Error())
}
return fmt.Sprintf("%s", plaintext)
}