-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
95 lines (73 loc) · 1.94 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
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"strings"
"github.com/mergermarket/go-pkcs7"
)
type CryptoKey struct {
key []byte
}
func New(secret string) CryptoKey {
key := []byte(secret)
return CryptoKey{key: key}
}
func (crypto CryptoKey) Encrypt(data string) (string, error) {
plainText := []byte(data)
plainText, err := pkcs7.Pad(plainText, aes.BlockSize)
if err != nil {
return "", fmt.Errorf(`plainText: "%s" has error`, plainText)
}
if len(plainText)%aes.BlockSize != 0 {
err = fmt.Errorf(`plainText: "%s" has the wrong block size`, plainText)
return "", err
}
block, err := aes.NewCipher(crypto.key)
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
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[aes.BlockSize:], plainText)
encryptedText := hex.EncodeToString(cipherText)
encrypted := encryptedText[:32] + ":" + encryptedText[32:]
return encrypted, nil
}
func (crypto CryptoKey) Decrypt(encrypted string) (string, error) {
if len(encrypted) <= 0 {
return "", nil
}
split := strings.Split(encrypted, ":")
encrypted = split[0] + split[1]
cipherText, err := hex.DecodeString(encrypted)
if err != nil {
return "", err
}
block, err := aes.NewCipher(crypto.key)
if err != nil {
return "", err
}
if len(cipherText) < aes.BlockSize {
return "", fmt.Errorf("cipherText too short")
}
iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]
if len(cipherText)%aes.BlockSize != 0 {
return "", fmt.Errorf("cipherText is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(cipherText, cipherText)
cipherText, err = pkcs7.Unpad(cipherText, aes.BlockSize)
if err != nil {
return "", err
}
return string(cipherText), nil
}