/
aes.go
88 lines (70 loc) · 1.96 KB
/
aes.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
package common
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"strings"
)
func AESEncrypt(key []byte, message string) (encmess string, err error) {
plainText := []byte(message)
block, err := aes.NewCipher(key)
if Error(err) {
return "", err
}
//IV needs to be unique, but doesn't have to be secure.
//It's common to put it at the beginning of the ciphertext.
cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
_, err = io.ReadFull(rand.Reader, iv)
if Error(err) {
return "", err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)
//returns to base64 encoded string
encmess = base64.StdEncoding.EncodeToString(cipherText)
return
}
func AESDecrypt(key []byte, securemess string) (decodedmess string, err error) {
cipherText, err := base64.StdEncoding.DecodeString(securemess)
if Error(err) {
return "", err
}
block, err := aes.NewCipher(key)
if Error(err) {
return "", err
}
if len(cipherText) < aes.BlockSize {
return "", errors.New("Ciphertext block size is too short!")
}
//IV needs to be unique, but doesn't have to be secure.
//It's common to put it at the beginning of the ciphertext.
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(cipherText, cipherText)
decodedmess = string(cipherText)
return
}
func IsStringEnrypted(password string) bool {
return strings.HasPrefix(password, "enc:")
}
func DecryptString(key []byte, txt string) (string, error) {
if IsStringEnrypted(txt) {
return AESDecrypt(key, txt[4:])
} else {
return txt, nil
}
}
func EncryptString(key []byte, txt string) (string, error) {
if !IsStringEnrypted(txt) {
password, err := AESEncrypt(key, txt)
return "enc:" + password, err
} else {
return txt, nil
}
}