-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
98 lines (78 loc) · 2 KB
/
helpers.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
package celeritas
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"os"
)
const (
randomString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+"
)
func (c *Celeritas) RandomString(n int) string {
s, r := make([]rune, n), []rune(randomString)
for i := range s {
p, _ := rand.Prime(rand.Reader, len(r))
x, y := p.Uint64(), uint64(len(r))
s[i] = r[x%y]
}
return string(s)
}
func (c *Celeritas) CreateDirIfNotExist(path string) error {
const mode = 0755
if _, err := os.Stat(path); os.IsNotExist(err) {
if err := os.Mkdir(path, mode); err != nil {
return err
}
}
return nil
}
func (c *Celeritas) CreateFileIfNotExist(path string) error {
var _, err = os.Stat(path)
if os.IsNotExist(err) {
file, err := os.Create(path)
if err != nil {
return err
}
defer func(file *os.File) {
_ = file.Close()
}(file)
}
return nil
}
type Encryption struct {
Key []byte
}
func (e *Encryption) Encrypt(text string) (string, error) {
//takes a string, encrypts it, then base46 encodes it
plainText := []byte(text)
block, err := aes.NewCipher(e.Key) //the key has to be 16, 24, or 32 bytes
if err != nil {
return "", err
}
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
return base64.URLEncoding.EncodeToString(cipherText), nil
}
func (e *Encryption) Decrypt(cryptoText string) (string, error) {
cipherText, _ := base64.URLEncoding.DecodeString(cryptoText)
block, err := aes.NewCipher(e.Key)
if err != nil {
return "", err
}
if len(cipherText) < aes.BlockSize {
return "", errors.New("cipherText too short")
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)
return string(cipherText), nil
}