-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
115 lines (103 loc) · 2.22 KB
/
crypto.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
110
111
112
113
114
115
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
)
var privateKey *rsa.PrivateKey
var key []byte
func InitCrypto() (err error) {
key, err = base64.StdEncoding.DecodeString(os.Getenv("aeskey"))
if err != nil {
return
}
if len(key) != 32 {
err = errors.New("Wrong aes key length")
return
}
privatePem, err := ioutil.ReadFile("./private.pem")
if err != nil {
fmt.Println(err)
return
}
block, _ := pem.Decode(privatePem)
pk, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return
}
privateKey = pk.(*rsa.PrivateKey)
privateKey.Precompute()
return
}
func Encrypt(data []byte) (baseText string, err error) {
c, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
baseText = base64.StdEncoding.EncodeToString(ciphertext)
return
}
func Decrypt(baseText string) (data []byte, err error) {
ciphertext, err := base64.StdEncoding.DecodeString(baseText)
if err != nil {
return
}
c, err := aes.NewCipher(key)
if err != nil {
return
}
gcm, err := cipher.NewGCM(c)
if err != nil {
return
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
err = errors.New("ciphertext size is less than nonceSize")
return
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
data, err = gcm.Open(nil, nonce, ciphertext, nil)
return
}
/*
func Encrypt(data string) (txt string, err error) {
label := []byte("OAEP Encrypted")
rng := rand.Reader
ciphertext, err := rsa.EncryptOAEP(sha512.New512_256(), rng, &privateKey.PublicKey, []byte(data), label)
if err != nil {
return
}
txt = base64.URLEncoding.EncodeToString(ciphertext)
return
}
func Decrypt(data string) (txt string, err error) {
ct, _ := base64.URLEncoding.DecodeString(data)
label := []byte("OAEP Encrypted")
rng := rand.Reader
plaintext, err := rsa.DecryptOAEP(sha512.New512_256(), rng, privateKey, ct, label)
if err != nil {
return
}
txt = string(plaintext)
return
}
*/