-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.go
55 lines (47 loc) · 1.37 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
package goutils
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
var bytesCrypt = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05}
// Encode a string to base64 string
func Base64(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
// Decode a base64 string to original string
func Base64Decode(s string) string {
decoded, err := base64.StdEncoding.DecodeString(s)
if err != nil {
Error(err)
return ""
}
return string(decoded)
}
// Encrypt method is to encrypt or hide any classified text
func Encrypt(text string) (string, error) {
block, err := aes.NewCipher([]byte(Env("SECRET_CRYPT_SEED", "")))
if err != nil {
return "", err
}
plainText := []byte(text)
cfb := cipher.NewCFBEncrypter(block, bytesCrypt)
cipherText := make([]byte, len(plainText))
cfb.XORKeyStream(cipherText, plainText)
return base64.StdEncoding.EncodeToString(cipherText), nil
}
// Decrypt method is to extract back the encrypted text
func Decrypt(text string) (string, error) {
block, err := aes.NewCipher([]byte(Env("SECRET_CRYPT_SEED", "")))
if err != nil {
return "", err
}
cipherText, err := base64.StdEncoding.DecodeString(text)
if err != nil {
return "", err
}
cfb := cipher.NewCFBDecrypter(block, bytesCrypt)
plainText := make([]byte, len(cipherText))
cfb.XORKeyStream(plainText, cipherText)
return string(plainText), nil
}