Skip to content

Commit

Permalink
feat: support selection of encryption and decryption methods, add gm …
Browse files Browse the repository at this point in the history
…sm4 crypto type
  • Loading branch information
destinyoooo committed Dec 25, 2024
1 parent 8d16d44 commit 5e909f1
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 6 deletions.
2 changes: 1 addition & 1 deletion docker/conf/config_sdb.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,4 @@ app_config:
- table: departments
columns: [ "dept_name" ]
aeskey: 123456789abcdefg
cryptoType: 4
cryptoType: aesgcm
2 changes: 1 addition & 1 deletion pkg/filter/crypto/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type ColumnCrypto struct {
Table string
Columns []string
AesKey string
CryptoType int
CryptoType misc.CryptoType
}

type columnIndex struct {
Expand Down
45 changes: 41 additions & 4 deletions pkg/misc/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"

"github.com/pkg/errors"
Expand All @@ -41,8 +42,44 @@ const (
CryptoSM4OFB
)

func CryptoEncrypt(data []byte, key []byte, iv []byte, cryptoType int) ([]byte, error) {
switch CryptoType(cryptoType) {
func (c *CryptoType) UnmarshalText(text []byte) error {
if c == nil {
return errors.New("can't unmarshal a nil *CryptoType")
}
if !c.unmarshalText(bytes.ToLower(text)) {
return fmt.Errorf("unrecognized protocol type: %q", text)
}
return nil
}

func (c *CryptoType) unmarshalText(text []byte) bool {
switch string(text) {
case "aesgcm":
*c = CryptoAESGCM
case "aescbc":
*c = CryptoAESCBC
case "aesecb":
*c = CryptoAESECB
case "aescfb":
*c = CryptoAESCFB
case "sm4gcm":
*c = CryptoSM4GCM
case "sm4ecb":
*c = CryptoSM4ECB
case "sm4cbc":
*c = CryptoSM4CBC
case "sm4cfb":
*c = CryptoSM4CFB
case "sm4ofb":
*c = CryptoSM4OFB
default:
return false
}
return true
}

func CryptoEncrypt(data []byte, key []byte, iv []byte, cryptoType CryptoType) ([]byte, error) {
switch cryptoType {
case CryptoAESGCM:
return AesEncryptGCM(data, key, iv)
case CryptoAESCBC:
Expand All @@ -66,8 +103,8 @@ func CryptoEncrypt(data []byte, key []byte, iv []byte, cryptoType int) ([]byte,
}
}

func CryptoDecrypt(encrypted []byte, key []byte, iv []byte, cryptoType int) ([]byte, error) {
switch CryptoType(cryptoType) {
func CryptoDecrypt(encrypted []byte, key []byte, iv []byte, cryptoType CryptoType) ([]byte, error) {
switch cryptoType {
case CryptoAESGCM:
return AesDecryptGCM(encrypted, key, iv)
case CryptoAESCBC:
Expand Down

0 comments on commit 5e909f1

Please sign in to comment.