-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypt.go
57 lines (52 loc) · 1.36 KB
/
crypt.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
package helpers
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"github.com/bocajim/helpers/log"
"io"
)
func encodeBase64(b []byte) []byte {
return []byte(base64.StdEncoding.EncodeToString(b))
}
func decodeBase64(b []byte) []byte {
data, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
panic(err)
}
return data
}
func Encrypt(key, text []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
log.Printf(log.Error, "Could not create new cipher using key: "+err.Error())
return nil
}
b := encodeBase64(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
log.Printf(log.Error, "Could not get random string: "+err.Error())
return nil
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
return ciphertext
}
func Decrypt(key, text []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
log.Printf(log.Error, "Could not create new cipher using key: "+err.Error())
return nil
}
if len(text) < aes.BlockSize {
log.Printf(log.Error, "Encrypted text was too short for the blocksize used.")
return nil
}
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
return decodeBase64(text)
}