Browse Source

fix:公私钥

duxin 1 year ago
parent
commit
0b1e854514
5 changed files with 70 additions and 92 deletions
  1. 7 3
      core/proxy/middleware/spiderPolyHandler.go
  2. 2 2
      core/util/http.go
  3. 58 86
      core/util/rsaEncDec.go
  4. 1 1
      etc/config.yaml
  5. 2 0
      main.go

+ 7 - 3
core/proxy/middleware/spiderPolyHandler.go

@@ -2,6 +2,7 @@ package middleware
 
 import (
 	"app.yhyue.com/moapp/jybase/common"
+	log "app.yhyue.com/moapp/jylog"
 	. "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
 	"bp.jydev.jianyu360.cn/BaseService/gateway/common/httpUtil"
 	"bp.jydev.jianyu360.cn/BaseService/gateway/core/proxy/filterPoly"
@@ -21,6 +22,7 @@ const (
 	VerifyPageHtmlSource  = "./resources/antiRes/page/%s.html"
 
 	JyAntiEncryptSign = "antiEncrypt"
+	JySecretKey       = "secretKey"
 )
 
 var filterPolyManager *filterPoly.Manager
@@ -95,17 +97,19 @@ func SpiderJsEncrypt(resp *http.Response) error {
 		if len(bytes) == 0 {
 			return nil, nil
 		}
-		var entryStr string
-		entryStr, err = util.JyAntiEncrypt(bytes, 9)
+		var entryStr, PKeyStr string
+		entryStr, PKeyStr, err = util.JyAntiEncrypt(bytes)
 		if err != nil {
+			log.Println("JyAntiEncrypt err: ", err.Error())
 			return
 		}
 		newBytes = gconv.Bytes(g.Map{
 			JyAntiEncryptSign: 1,
+			JySecretKey:       PKeyStr,
 			"data":            entryStr,
 		})
 		resp.Header.Add(JyAntiEncryptSign, "1")
-		resp.Header.Add("", "")
+		//resp.Header.Add(JySecretKey, PKeyStr)
 		return
 	})
 }

+ 2 - 2
core/util/http.go

@@ -146,8 +146,8 @@ func ChangeResponse(resp *http.Response, fn func([]byte) ([]byte, error)) (err e
 	newContent, err = fn(content)
 	if err != nil {
 		g.Log().Errorf(ctx, "changeRes func %v err %v", fn, err)
-	} else {
-		newContent = content
+		//} else {
+		//	newContent = content
 	}
 
 	var zBuf bytes.Buffer

+ 58 - 86
core/util/rsaEncDec.go

@@ -1,8 +1,8 @@
 package util
 
 import (
-	log "app.yhyue.com/moapp/jylog"
-	"context"
+	"crypto/aes"
+	"crypto/cipher"
 	"crypto/rand"
 	"crypto/rsa"
 	"crypto/x509"
@@ -11,33 +11,24 @@ import (
 	"errors"
 	"fmt"
 	"github.com/gogf/gf/v2/frame/g"
+	"github.com/gogf/gf/v2/os/gctx"
+	"io"
 	"io/ioutil"
-	"math/big"
+	"log"
 )
 
 var (
-	PublicKey    *rsa.PublicKey
-	PrivateKey   *rsa.PrivateKey
-	Displacement int64 = 9
-	ctx                = context.TODO()
+	PublicKey  *rsa.PublicKey
+	PrivateKey *rsa.PrivateKey
 )
 
-func init() {
-	//initPrivatePublicKey()
-}
-
-func JyAntiEncrypt(in []byte, pos int) (out string, err error) {
-	return base64.StdEncoding.EncodeToString(in), err
-}
-
-func initPrivatePublicKey() {
+func InitPrivatePublicKey() {
 	// 读取私钥文件
 	privateKeyBytes, err := ioutil.ReadFile("./etc/rsa_private_key.pem")
 	if err != nil {
-		g.Log().Errorf(ctx, "无法读取私钥文件:%v", err)
+		log.Println("无法读取私钥文件:", err)
 		return
 	}
-
 	// 解码私钥
 	privateKeyBlock, _ := pem.Decode(privateKeyBytes)
 	if privateKeyBlock == nil || privateKeyBlock.Type != "PRIVATE KEY" {
@@ -59,14 +50,13 @@ func initPrivatePublicKey() {
 		return
 	}
 	PrivateKey = rsaPrivateKey
-
 	// 读取公钥文件
 	publicKeyBytes, err := ioutil.ReadFile("./etc/rsa_public_key.pem")
 	if err != nil {
 		log.Println("无法读取公钥文件:", err)
 		return
 	}
-
+	log.Println("读取公钥文件")
 	// 解码公钥
 	publicKeyBlock, _ := pem.Decode(publicKeyBytes)
 	if publicKeyBlock == nil || publicKeyBlock.Type != "PUBLIC KEY" {
@@ -88,87 +78,69 @@ func initPrivatePublicKey() {
 		return
 	}
 	PublicKey = rsaPublicKey
-	//Displacement = g.Cfg().MustGet(gctx.New(), "displacement", 9).Int64()
-}
-
-// DisplacementEncryption 位移加密
-func DisplacementEncryption(content string) (string, error) {
-	if content == "" {
-		return "", errors.New("加密内容为空")
-	}
-	if PrivateKey == nil {
-		return "", errors.New("无效私钥")
-	}
+	log.Println("初始化公钥成功", PublicKey)
+	//对称key加密
+	//AesEncDecKey = g.Cfg().MustGet(gctx.New(), "aesEncDecKey").String()
+	//使用非对称加密key
+	//shiftValue := big.NewInt(g.Cfg().MustGet(ctx, "pos").Int64())
+	//PublicKey.E = int(shiftValue.Int64())
 
-	plaintext := []byte(content)
-	shiftValue := big.NewInt(Displacement)
-	PrivateKey.D = new(big.Int).Mul(PrivateKey.D, shiftValue)
-	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, &PrivateKey.PublicKey, plaintext)
-	if err != nil {
-		fmt.Println("加密失败:", err)
-		return "", err
-	}
-	return string(ciphertext), nil
 }
 
-// DisplacementDecryption 位移解密
-func DisplacementDecryption(content string) (string, error) {
-	if content == "" {
-		return "", errors.New("解密内容为空")
+func JyAntiEncrypt(plaintext []byte) (out, PKeyStr string, err error) {
+	if plaintext == nil {
+		return
 	}
-	if PrivateKey == nil {
-		return "", errors.New("无效私钥")
+	if PublicKey == nil {
+		err = errors.New("无效公钥")
+		return
 	}
-	exponent := big.NewInt(Displacement) // 位移处理的值
-	PrivateKey.D = new(big.Int).Mul(PrivateKey.D, exponent)
-	ciphertext, err := base64.StdEncoding.DecodeString(content)
-	if err != nil {
-		log.Println("密文解码失败:", err)
-		return "", errors.New("密文解码失败")
+	aesEncDecKey := g.Cfg().MustGet(gctx.New(), "aesEncDecKey").String()
+	if aesEncDecKey == "" {
+		err = errors.New("密钥获取失败")
+		return
 	}
-
-	// 使用私钥解密数据
-	decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, PrivateKey, ciphertext)
+	out, err = Encrypt(plaintext, []byte(aesEncDecKey))
 	if err != nil {
-		log.Println("解密失败:", err)
-		return "", err
+		return
+	}
+	//非对称加密
+	var pKeyByte []byte
+	pKeyByte, err = rsa.EncryptPKCS1v15(rand.Reader, PublicKey, []byte(aesEncDecKey))
+	if err == nil {
+		PKeyStr = base64.StdEncoding.EncodeToString(pKeyByte)
 	}
-	return string(decryptedText), nil
+	log.Println("key加密前===", aesEncDecKey)
+	log.Println("key加密后===", PKeyStr)
+	//log.Println("加密后内容===", out)
+	return
 }
 
-// Encryption  加密
-func Encryption(content string) (string, error) {
-	if content == "" {
-		return "", errors.New("加密内容为空")
-	}
-	plaintext := []byte(content)
-	// 使用公钥加密数据
-	ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, PublicKey, plaintext)
+// 对称加密
+func Encrypt(plaintext []byte, key []byte) (string, error) {
+	block, err := aes.NewCipher(key)
 	if err != nil {
-		log.Println("加密失败:", err)
 		return "", err
 	}
-	return string(ciphertext), nil
-}
 
-func Decryption(content string) (string, error) {
-	if content == "" {
-		return "", errors.New("解密内容为空")
-	}
-	if PrivateKey == nil {
-		return "", errors.New("无效私钥")
-	}
-	ciphertext, err := base64.StdEncoding.DecodeString(content)
-	if err != nil {
-		log.Println("密文解码失败:", err)
-		return "", errors.New("密文解码失败")
-	}
+	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
 
-	// 使用私钥解密数据
-	decryptedText, err := rsa.DecryptPKCS1v15(rand.Reader, PrivateKey, ciphertext)
-	if err != nil {
-		log.Println("解密失败:", err)
+	iv := ciphertext[:aes.BlockSize]
+	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
 		return "", err
 	}
-	return string(decryptedText), nil
+
+	stream := cipher.NewCTR(block, iv)
+	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
+
+	return base64.StdEncoding.EncodeToString(ciphertext), nil
 }
+
+/*func JyAntiDoc(plaintext []byte, pos int) (out string, err error) {
+	if plaintext == nil {
+		return "", errors.New("加密内容为空")
+	}
+	//exponent := big.NewInt(int64(pos)) // 位移处理的值
+	//PrivateKey.D = new(big.Int).Mul(PrivateKey.D, exponent)
+	return string(PrivateKey.D.Bytes()), nil
+}*/

+ 1 - 1
etc/config.yaml

@@ -136,4 +136,4 @@ noPowerUrlSwitch:
   '/succbi/nzj/app/nzj.app/nzj_detail_1.spg' : '/succbi/nzj/app/nzj.app/nzj_detail_0.spg'
   '/succbi/nzj/app/nzj.app/nzj_search_1.spg': '/succbi/nzj/app/nzj.app/nzj_search_0.spg'
 
-displacement: 123
+aesEncDecKey: jianyu0123456789

+ 2 - 0
main.go

@@ -7,6 +7,7 @@ import (
 	"bp.jydev.jianyu360.cn/BaseService/gateway/core/proxy"
 	"bp.jydev.jianyu360.cn/BaseService/gateway/core/proxy/middleware"
 	"bp.jydev.jianyu360.cn/BaseService/gateway/core/proxy/rpc"
+	"bp.jydev.jianyu360.cn/BaseService/gateway/core/util"
 	"github.com/gogf/gf/contrib/trace/jaeger/v2"
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/os/gcfg"
@@ -19,6 +20,7 @@ func init() {
 	logs.InitLogs()                                                           // 初始化日志组件
 	rpc.InitBaseServerRpc()                                                   // 初始化rpc服务连接
 	middleware.InitFilterPolyManager()                                        // 初始化
+	util.InitPrivatePublicKey()                                               //初始化公钥
 }
 
 func main() {