Browse Source

新增数据加密

317699326@qq.com 5 days ago
parent
commit
021b7e8e7e
6 changed files with 221 additions and 40 deletions
  1. 14 0
      controllers/base_auth.go
  2. 13 0
      controllers/base_common.go
  3. 0 40
      utils/common.go
  4. 3 0
      utils/config.go
  5. 4 0
      utils/constants.go
  6. 187 0
      utils/des3.go

+ 14 - 0
controllers/base_auth.go

@@ -171,6 +171,9 @@ func (c *BaseAuthController) ServeJSON(encoding ...bool) {
 
 func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
 	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
+	desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
+	c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
+
 	var content []byte
 	var err error
 	if hasIndent {
@@ -191,6 +194,17 @@ func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool)
 		requestBody = c.Ctx.Input.URI()
 	}
 	c.logUri(content, requestBody, ip)
+	//if coding {
+	//	content = []byte(utils.StringsToJSON(string(content)))
+	//}
+	//if utils.RunMode != "debug" {
+	//	content = utils.DesBase64Encrypt(content, utils.DesKey)
+	//	// get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
+	//	content = []byte(`"` + string(content) + `"`)
+	//}
+	content = utils.DesBase64Encrypt(content, utils.DesKey)
+	// get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
+	content = []byte(`"` + string(content) + `"`)
 	if coding {
 		content = []byte(utils.StringsToJSON(string(content)))
 	}

+ 13 - 0
controllers/base_common.go

@@ -56,6 +56,8 @@ func (c *BaseCommonController) ServeJSON(encoding ...bool) {
 
 func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding bool) error {
 	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
+	desEncrypt := utils.DesBase64Encrypt([]byte(utils.DesKey), utils.DesKeySalt)
+	c.Ctx.Output.Header("Dk", string(desEncrypt)) // des3加解密key
 	var content []byte
 	var err error
 	if hasIndent {
@@ -73,6 +75,17 @@ func (c *BaseCommonController) JSON(data interface{}, hasIndent bool, coding boo
 	fmt.Println(params)
 	requestBody, _ := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
 	c.logUri(content, requestBody, ip)
+	//if coding {
+	//	content = []byte(utils.StringsToJSON(string(content)))
+	//}
+	//if utils.RunMode != "debug" {
+	//	content = utils.DesBase64Encrypt(content, utils.DesKey)
+	//	// get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
+	//	content = []byte(`"` + string(content) + `"`)
+	//}
+	content = utils.DesBase64Encrypt(content, utils.DesKey)
+	// get请求时,不加双引号就获取不到数据,不知道什么原因,所以还是在前后加上双引号吧
+	content = []byte(`"` + string(content) + `"`)
 	if coding {
 		content = []byte(utils.StringsToJSON(string(content)))
 	}

+ 0 - 40
utils/common.go

@@ -2,8 +2,6 @@ package utils
 
 import (
 	"bufio"
-	"crypto/cipher"
-	"crypto/des"
 	"crypto/md5"
 	"crypto/sha1"
 	"encoding/base64"
@@ -1204,44 +1202,6 @@ func DateConvMysqlConvMongo(dateCon string) string {
 	return cond
 }
 
-func DesBase64Decrypt(crypted []byte, desKey string) []byte {
-	result, _ := base64.StdEncoding.DecodeString(string(crypted))
-	remain := len(result) % 8
-	if remain > 0 {
-		mod := 8 - remain
-		for i := 0; i < mod; i++ {
-			result = append(result, 0)
-		}
-	}
-	origData, err := TripleDesDecrypt(result, []byte(desKey))
-	if err != nil {
-		panic(any(err))
-	}
-	return origData
-}
-
-// // 3DES解密
-func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
-	block, err := des.NewTripleDESCipher(key)
-	if err != nil {
-		return nil, err
-	}
-	blockMode := cipher.NewCBCDecrypter(block, key[:8])
-	origData := make([]byte, len(crypted))
-	// origData := crypted
-	blockMode.CryptBlocks(origData, crypted)
-	origData = PKCS5UnPadding(origData)
-	// origData = ZeroUnPadding(origData)
-	return origData, nil
-}
-
-func PKCS5UnPadding(origData []byte) []byte {
-	length := len(origData)
-	// 去掉最后一个字节 unpadding 次
-	unpadding := int(origData[length-1])
-	return origData[:(length - unpadding)]
-}
-
 func TimeTransferString(format string, t time.Time) string {
 	str := t.Format(format)
 	if t.IsZero() {

+ 3 - 0
utils/config.go

@@ -41,6 +41,7 @@ var (
 	EmailSendToUsers string
 	// AlarmMsgUrl 报警服务地址
 	AlarmMsgUrl string
+	DesKey      string // 接口返回加密KEY
 )
 
 // 公共api内部服务调用
@@ -176,6 +177,8 @@ func init() {
 		ETA_FORUM_HUB_NAME_EN = config["eta_forum_hub_name_en"]
 		ETA_FORUM_HUB_MD5_KEY = config["eta_forum_hub_md5_key"]
 	}
+	// 接口返回加密KEY
+	DesKey = config["des_key"]
 }
 
 // FormatMixTableDataShowValue 格式化自定表格显示数据

+ 4 - 0
utils/constants.go

@@ -253,3 +253,7 @@ const (
 	DbNameAI          = "eta_ai"
 	DbNameWeekly      = "weekly_report"
 )
+
+const (
+	DesKeySalt = "JMCqSoUrTAmyNNIRb0TtlrPk" // DesKey盐值
+)

+ 187 - 0
utils/des3.go

@@ -0,0 +1,187 @@
+// 加密工具类,用了3des和base64
+package utils
+
+import (
+	"bytes"
+	"crypto/cipher"
+	"crypto/des"
+	"encoding/base64"
+	"encoding/hex"
+	"errors"
+	"strings"
+)
+
+// des3 + base64 encrypt
+func DesBase64Encrypt(origData []byte, desKey string) []byte {
+	result, err := TripleDesEncrypt(origData, []byte(desKey))
+	if err != nil {
+		panic(any(err))
+	}
+	return []byte(base64.StdEncoding.EncodeToString(result))
+}
+
+func DesBase64Decrypt(crypted []byte, desKey string) []byte {
+	result, _ := base64.StdEncoding.DecodeString(string(crypted))
+	remain := len(result) % 8
+	if remain > 0 {
+		mod := 8 - remain
+		for i := 0; i < mod; i++ {
+			result = append(result, 0)
+		}
+	}
+	origData, err := TripleDesDecrypt(result, []byte(desKey))
+	if err != nil {
+		panic(any(err))
+	}
+	return origData
+}
+
+// 3DES加密
+func TripleDesEncrypt(origData, key []byte) ([]byte, error) {
+	block, err := des.NewTripleDESCipher(key)
+	if err != nil {
+		return nil, err
+	}
+	origData = PKCS5Padding(origData, block.BlockSize())
+	// origData = ZeroPadding(origData, block.BlockSize())
+	blockMode := cipher.NewCBCEncrypter(block, key[:8])
+	crypted := make([]byte, len(origData))
+	blockMode.CryptBlocks(crypted, origData)
+	return crypted, nil
+}
+
+// 3DES解密
+func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
+	block, err := des.NewTripleDESCipher(key)
+	if err != nil {
+		return nil, err
+	}
+	blockMode := cipher.NewCBCDecrypter(block, key[:8])
+	origData := make([]byte, len(crypted))
+	// origData := crypted
+	blockMode.CryptBlocks(origData, crypted)
+	origData = PKCS5UnPadding(origData)
+	// origData = ZeroUnPadding(origData)
+	return origData, nil
+}
+
+func ZeroPadding(ciphertext []byte, blockSize int) []byte {
+	padding := blockSize - len(ciphertext)%blockSize
+	padtext := bytes.Repeat([]byte{0}, padding)
+	return append(ciphertext, padtext...)
+}
+
+func ZeroUnPadding(origData []byte) []byte {
+	length := len(origData)
+	unpadding := int(origData[length-1])
+	return origData[:(length - unpadding)]
+}
+
+func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
+	padding := blockSize - len(ciphertext)%blockSize
+	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
+	return append(ciphertext, padtext...)
+}
+
+func PKCS5UnPadding(origData []byte) []byte {
+	length := len(origData)
+	// 去掉最后一个字节 unpadding 次
+	unpadding := int(origData[length-1])
+	return origData[:(length - unpadding)]
+}
+
+// DES加密
+func DesEncrypt(content string, key string) string {
+	contents := []byte(content)
+	keys := []byte(key)
+	block, err := des.NewCipher(keys)
+	if err != nil {
+		return ""
+	}
+	contents = PKCS5Padding(contents, block.BlockSize())
+	blockMode := cipher.NewCBCEncrypter(block, keys)
+	crypted := make([]byte, len(contents))
+	blockMode.CryptBlocks(crypted, contents)
+	return byteToHexString(crypted)
+}
+
+func byteToHexString(bytes []byte) string {
+	str := ""
+	for i := 0; i < len(bytes); i++ {
+		sTemp := hex.EncodeToString([]byte{bytes[i]})
+		if len(sTemp) < 2 {
+			str += string(0)
+		}
+		str += strings.ToUpper(sTemp)
+	}
+	return str
+}
+
+// DES解密
+func DesDecrypt(content string, key string) string {
+	contentBytes, err := hex.DecodeString(content)
+	if err != nil {
+		return "字符串转换16进制数组失败" + err.Error()
+	}
+	keys := []byte(key)
+	block, err := des.NewCipher(keys)
+	if err != nil {
+		return "解密失败" + err.Error()
+	}
+	blockMode := cipher.NewCBCDecrypter(block, keys)
+	origData := contentBytes
+	blockMode.CryptBlocks(origData, contentBytes)
+	origData = ZeroUnPadding(origData)
+	return string(origData)
+}
+
+// DES ECB PKCK5Padding
+func EntryptDesECB(data, key []byte) (string, error) {
+	if len(key) > 8 {
+		key = key[:8]
+	}
+	block, err := des.NewCipher(key)
+	if err != nil {
+		return "", errors.New("des.NewCipher " + err.Error())
+	}
+	bs := block.BlockSize()
+	data = PKCS5Padding(data, bs)
+	if len(data)%bs != 0 {
+		return "", errors.New("EntryptDesECB Need a multiple of the blocksize")
+	}
+	out := make([]byte, len(data))
+	dst := out
+	for len(data) > 0 {
+		block.Encrypt(dst, data[:bs])
+		data = data[bs:]
+		dst = dst[bs:]
+	}
+	return base64.StdEncoding.EncodeToString(out), nil
+}
+
+func DecryptDESECB(d string, key []byte) ([]byte, error) {
+	data, err := base64.StdEncoding.DecodeString(d)
+	if err != nil {
+		return nil, errors.New("decodebase64 " + err.Error())
+	}
+	if len(key) > 8 {
+		key = key[:8]
+	}
+	block, err := des.NewCipher(key)
+	if err != nil {
+		return nil, errors.New("des.NewCipher " + err.Error())
+	}
+	bs := block.BlockSize()
+	if len(data)%bs != 0 {
+		return nil, errors.New("DecryptDES crypto/cipher: input not full blocks")
+	}
+	out := make([]byte, len(data))
+	dst := out
+	for len(data) > 0 {
+		block.Decrypt(dst, data[:bs])
+		data = data[bs:]
+		dst = dst[bs:]
+	}
+	out = PKCS5UnPadding(out)
+	return out, nil
+}