Skip to content

Commit

Permalink
upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
xinliangnote committed Dec 26, 2020
1 parent 155f5fc commit 34f85ad
Show file tree
Hide file tree
Showing 12 changed files with 345 additions and 118 deletions.
43 changes: 43 additions & 0 deletions configs/fat_configs.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,46 @@
host = '127.0.0.1'
port = 3306

[aes]
key = 'IgkibX71IEf382PT'
iv = 'IgkibX71IEf382PT'

[rsa]
private = '-----BEGIN RSA PRIVATE KEY-----
MIIEpgIBAAKCAQEA1O3p0JN0/RrP7eY3f81izPf16FS0WMNGCJkd+y5c6yBzUvN0
IEeoxiIWIBhoMKH0pzlzBg0rfttojSodOgNom/UCAzAYEgdIsNee5LSN/7e0T2/Q
vsIAHINuA8gI8fGoGiSA2TEzpUo6aVXwhZT34GGRdrSJ+m4iVk/Kt95tavBNk+ND
VSeb5xAjxBchT5BjAMMlE0ffGZb0MMjjO5+e9Tn8f99M2VMqpzXHXZzv1ABmqufz
S20iWcSvnjhWcJ9hiKwO8Z30GgJyACmml+HMxLYEFN9h2MWYgxLm9Z0rLMrWwMM+
E2rCs8tsxAD5sO9RZMJPl1C0FIsMR53ngqbzowIDAQABAoIBAQCO1RE1ItUlO6kj
Un0ENAgEqojAUqGvsT33Yo7kAZO+/cOeb0UEqk0iq5bf7L9ncBynWDg6ZPc6X3/g
wdFdKxAvHck9zjM3VL+EMP+bNyrR0K8ZYk5Kx+Q/PEK+Mp8dfRdgggAUsZaNWB+a
rVVspiMo1wo28KBl5x8NevTnJkOLqXAyB7UyLWqnOL1fb988lZvZPR7ZUYroVIZa
pyXtZcafIJeKyQ3bvWI5+eFqOe61Z4Bx1+TpfZ3fKfSDW0vhxzNqaimOa8jSXtMJ
jMeOctL4nZ0TPo/jS3I+XlaH4ZQlFLuUWGscpxwfEeBN23I8HRLkZXJsw66yvRN3
s4bUKPXRAoGBAP/3oSZAECvfsYYzs76tnrAmR/0GxCqgguxDlWn5Dow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2TEzpUo6aVXwhZT3
4GGRdrSJ+m4iVk/Kt95tavBNk+NDVSeb5xAjxBchT5BjAMMlE0ffGZb0MMjjO5+e
9Tn8f99M2VMqpzXHXZzv1ABmqufzS20iWcSvnjhWcJ9hiKwO8Z30GgJyACmml+HM
xLYEFN9h2MWYgxLm9Z0rLMrWwMM+E2rCs8tsxAD5sO9RZMJPl1C0FIsMR53ngqbz
owIDAQAB
-----END PUBLIC KEY-----'

81 changes: 81 additions & 0 deletions internal/api/controller/demo/demo.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package demo

import (
"fmt"
"net/url"
"time"

"github.com/xinliangnote/go-gin-api/internal/pkg/configs"
"github.com/xinliangnote/go-gin-api/internal/pkg/core"
"github.com/xinliangnote/go-gin-api/internal/pkg/errno"
"github.com/xinliangnote/go-gin-api/internal/pkg/jsonparse"
"github.com/xinliangnote/go-gin-api/pkg/aes"
"github.com/xinliangnote/go-gin-api/pkg/httpclient"
"github.com/xinliangnote/go-gin-api/pkg/md5"
"github.com/xinliangnote/go-gin-api/pkg/rsa"

"go.uber.org/zap"
)
Expand Down Expand Up @@ -116,3 +121,79 @@ func (d *Demo) User() core.HandlerFunc {
c.SetPayload(errno.OK.WithData(data))
}
}

func (d *Demo) RsaTest() core.HandlerFunc {

return func(c core.Context) {
startTime := time.Now()
encryptStr := "param_1=xxx&param_2=xxx&ak=xxx&ts=1111111111"
count := 500

cfg := configs.Get()
rsaPublic := rsa.NewPublic(cfg.Rsa.Public)
rsaPrivate := rsa.NewPrivate(cfg.Rsa.Private)

for i := 0; i < count; i++ {
// 生成签名
sn, err := rsaPublic.Encrypt(encryptStr)
if err != nil {
d.logger.Error("rsa public encrypt err", zap.Error(err))
}

// 验证签名
_, err = rsaPrivate.Decrypt(sn)
if err != nil {
d.logger.Error("rsa private decrypt err", zap.Error(err))
}
}
c.SetPayload(errno.OK.
WithData(fmt.Sprintf("%v次 - %v", count, time.Since(startTime))),
)
}
}

func (d *Demo) AesTest() core.HandlerFunc {
return func(c core.Context) {
startTime := time.Now()
encryptStr := "param_1=xxx&param_2=xxx&ak=xxx&ts=1111111111"
count := 1000000

cfg := configs.Get()
aes := aes.New(cfg.Aes.Key, cfg.Aes.Iv)
for i := 0; i < count; i++ {
// 生成签名
sn, err := aes.Encrypt(encryptStr)
if err != nil {
d.logger.Error("aes encrypt err", zap.Error(err))
}

// 验证签名
_, err = aes.Decrypt(sn)
if err != nil {
d.logger.Error("aes decrypt err", zap.Error(err))
}
}
c.SetPayload(errno.OK.
WithData(fmt.Sprintf("%v次 - %v", count, time.Since(startTime))))
}
}

func (d *Demo) MD5Test() core.HandlerFunc {
return func(c core.Context) {
startTime := time.Now()
encryptStr := "param_1=xxx&param_2=xxx&ak=xxx&ts=1111111111"
count := 1000000

md5 := md5.New()
for i := 0; i < count; i++ {
// 生成签名
md5.Encrypt(encryptStr)

// 验证签名
md5.Encrypt(encryptStr)
}
c.SetPayload(errno.OK.
WithData(fmt.Sprintf("%v次 - %v", count, time.Since(startTime))),
)
}
}
57 changes: 0 additions & 57 deletions internal/api/controller/test/test.go

This file was deleted.

17 changes: 4 additions & 13 deletions internal/api/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,14 @@ func NewHTTPMux(logger *zap.Logger) (core.Mux, error) {
d.GET("get/:name", demoHandler.Get(), core.DisableJournal)
d.POST("post", demoHandler.Post(), core.DisableJournal)

// 测试加密性能
d.GET("/rsa/test", demoHandler.RsaTest())
d.GET("/aes/test", demoHandler.AesTest())
d.GET("/md5/test", demoHandler.MD5Test())
}

// 测试链路追踪
//mux.GET("/jaeger_test", jaeger_conn.JaegerTest)

// 测试加密性能
//TestRouter := mux.Group("/test")
//{
// // 测试 MD5 组合 的性能
// TestRouter.GET("/md5", core.Handle(test.Md5Test))
//
// // 测试 AES 的性能
// TestRouter.GET("/aes", core.Handle(test.AesTest))
//
// // 测试 RSA 的性能
// TestRouter.GET("/rsa", core.Handle(test.RsaTest))
//}

return mux, nil
}
12 changes: 9 additions & 3 deletions internal/pkg/configs/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@ type Config struct {
Port int `mapstructure:"port"`
} `mapstructure:"db"`

Signature struct {
Secrets map[string]string `mapstructure:"secrets"`
} `mapstructure:"signature"`
Aes struct {
Key string `mapstructure:"key"`
Iv string `mapstructure:"iv"`
} `mapstructure:"aes"`

Rsa struct {
Private string `mapstructure:"private"`
Public string `mapstructure:"public"`
} `mapstructure:"rsa"`
}

func init() {
Expand Down
7 changes: 3 additions & 4 deletions internal/pkg/core/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ type Context interface {
Logger() *zap.Logger
setLogger(logger *zap.Logger)

GetPayload() interface{}
GetPayload() errno.Error
SetPayload(payload errno.Error)

Header() http.Header
Expand Down Expand Up @@ -178,13 +178,12 @@ func (c *context) setLogger(logger *zap.Logger) {
c.ctx.Set(_LoggerName, logger)
}

func (c *context) GetPayload() interface{} {
func (c *context) GetPayload() errno.Error {
payload, _ := c.ctx.Get(_PayloadName)
return payload
return payload.(errno.Error)
}

func (c *context) SetPayload(payload errno.Error) {
payload.WithID(c.Journal().ID())
c.ctx.Set(_PayloadName, payload)
}

Expand Down
13 changes: 8 additions & 5 deletions internal/pkg/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,19 +262,22 @@ func New(logger *zap.Logger, options ...Option) (Mux, error) {
}
}

if ctx.Writer.Status() == http.StatusNotFound {
return
}

response := context.GetPayload()
if x := context.Journal(); x != nil {
context.SetHeader(journal.JournalHeader, x.ID())
response.WithID(x.ID())
} else {
response.WithID("")
}

response := context.GetPayload()
if response != nil {
ctx.JSON(http.StatusOK, response)
}

if ctx.Writer.Status() == http.StatusNotFound {
return
}

var j *journal.Journal
if x := context.Journal(); x != nil {
j = x.(*journal.Journal)
Expand Down
80 changes: 80 additions & 0 deletions pkg/aes/aes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package aes

import (
"bytes"
cryptoAes "crypto/aes"
"crypto/cipher"
"encoding/base64"
)

var _ Aes = (*aes)(nil)

type Aes interface {
i()
// Encrypt 加密
Encrypt(encryptStr string) (string, error)

// Decrypt 解密
Decrypt(decryptStr string) (string, error)
}

type aes struct {
key string
iv string
}

func New(key, iv string) Aes {
return &aes{
key: key,
iv: iv,
}
}

func (a *aes) i() {}

func (a *aes) Encrypt(encryptStr string) (string, error) {
encryptBytes := []byte(encryptStr)
block, err := cryptoAes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}

blockSize := block.BlockSize()
encryptBytes = pkcs5Padding(encryptBytes, blockSize)

blockMode := cipher.NewCBCEncrypter(block, []byte(a.iv))
encrypted := make([]byte, len(encryptBytes))
blockMode.CryptBlocks(encrypted, encryptBytes)
return base64.URLEncoding.EncodeToString(encrypted), nil
}

func (a *aes) Decrypt(decryptStr string) (string, error) {
decryptBytes, err := base64.URLEncoding.DecodeString(decryptStr)
if err != nil {
return "", err
}

block, err := cryptoAes.NewCipher([]byte(a.key))
if err != nil {
return "", err
}

blockMode := cipher.NewCBCDecrypter(block, []byte(a.iv))
decrypted := make([]byte, len(decryptBytes))

blockMode.CryptBlocks(decrypted, decryptBytes)
decrypted = pkcs5UnPadding(decrypted)
return string(decrypted), nil
}

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(decrypted []byte) []byte {
length := len(decrypted)
unPadding := int(decrypted[length-1])
return decrypted[:(length - unPadding)]
}
Loading

0 comments on commit 34f85ad

Please sign in to comment.