-
Notifications
You must be signed in to change notification settings - Fork 0
/
sm4.go
50 lines (44 loc) · 1.18 KB
/
sm4.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
package crypto
import (
"github.com/forestyc/playground/pkg/security/encoding"
"github.com/pkg/errors"
"github.com/tjfoc/gmsm/sm4"
)
type SM4 struct {
}
// Encrypt 加密
func (s SM4) Encrypt(data []byte, key []byte) ([]byte, error) {
if len(data) == 0 || len(key) == 0 {
return nil, errors.New("invalid params")
}
return sm4.Sm4Ecb(key, data, true)
}
// Decrypt 解密
func (s SM4) Decrypt(data []byte, key []byte) ([]byte, error) {
if len(data) == 0 || len(key) == 0 {
return nil, errors.New("invalid params")
}
return sm4.Sm4Ecb(key, data, false)
}
// EncryptWithBase64 加密,使用base64
func (s SM4) EncryptWithBase64(data []byte, key []byte) (string, error) {
if len(data) == 0 || len(key) == 0 {
return "", errors.New("invalid params")
}
crypto, err := s.Encrypt(data, key)
if err != nil {
return "", err
}
return encoding.Base64Encode(crypto), nil
}
// DecryptWithBase64 解密,使用base64
func (s SM4) DecryptWithBase64(data string, key []byte) ([]byte, error) {
if len(data) == 0 || len(key) == 0 {
return nil, errors.New("invalid params")
}
crypto, err := encoding.Base64Decode(data)
if err != nil {
return nil, err
}
return s.Decrypt(crypto, key)
}