diff --git a/app/constants/common/common.go b/app/constants/common/common.go index 7051a80..328530c 100644 --- a/app/constants/common/common.go +++ b/app/constants/common/common.go @@ -1,10 +1,10 @@ package common const ( - TOKEN_PRE = "player_token_" - TOKEN_Admin = "Admin_token_" - ADMIN_V1 = "/pay/admin/api/v1" - FRONT_API_V1 = "/v1" + TOKEN_PRE = "player_token_" + TOKEN_Admin = "Admin_token_" + ADMIN_V1 = "/pay/admin/api/v1 + FRONT_V1 = "/api/v1" // 支付渠道枚举,1微信JSAPI,2微信H5,3微信app,4微信Native,5微信小程序,6支付宝网页&移动应用,7支付宝小程序,8支付宝JSAPI PAY_CHANNEL_UNKNOWN = 0 diff --git a/app/constants/errorcode/error_code.go b/app/constants/errorcode/error_code.go index 5819d91..e416628 100644 --- a/app/constants/errorcode/error_code.go +++ b/app/constants/errorcode/error_code.go @@ -19,14 +19,21 @@ const ( //系统错误 SystemError = 500 + //请求超时 + RequestTimeOut = 600 + //未登录 NotLogin = 1000 // 商户 MerchantNotFound = 1100 - AppNotFound = 1200 + // app + AppNotFound = 1200 + AppDisabled = 1201 + AppIpNotAllow = 1202 + //渠道 PayChannelNotFound = 1300 ) @@ -40,14 +47,16 @@ var MsgEN = map[int]string{ } var MsgZH = map[int]string{ - Success: "请求成功", - ParamError: "参数错误", - NotFound: "数据不存在", - NotAuth: "未经授权", - NotLogin: "未登录", - - MerchantNotFound: "商户不存在", - AppNotFound: "应用不存在", + Success: "请求成功", + ParamError: "参数错误", + NotFound: "数据不存在", + NotAuth: "未经授权", + NotLogin: "未登录", + RequestTimeOut: "请求超时", + MerchantNotFound: "商户不存在", + AppNotFound: "app_id未找到", + AppDisabled: "app通道关闭", + AppIpNotAllow: "ip不在白名单内", PayChannelNotFound: "支付方式不存在", } var MsgMap map[string]map[int]string = map[string]map[int]string{"en": MsgZH} diff --git a/app/constants/pojo/app.go b/app/constants/pojo/app.go new file mode 100644 index 0000000..29f0239 --- /dev/null +++ b/app/constants/pojo/app.go @@ -0,0 +1,7 @@ +package pojo + +const ( + Rsa int32 = iota + 1 + Sm2 + Sm4 +) diff --git a/app/constants/pojo/common.go b/app/constants/pojo/common.go new file mode 100644 index 0000000..1e58d13 --- /dev/null +++ b/app/constants/pojo/common.go @@ -0,0 +1,6 @@ +package pojo + +const ( + STATUS_ENABLE int32 = 1 + STATUS_DISABLED int32 = 2 +) diff --git a/app/data/app.go b/app/data/app.go index adabe1a..f355d0f 100644 --- a/app/data/app.go +++ b/app/data/app.go @@ -3,6 +3,7 @@ package data import ( "PaymentCenter/app/http/entities" "PaymentCenter/app/models/appmodel" + "database/sql" "xorm.io/builder" "xorm.io/xorm" ) @@ -38,6 +39,11 @@ func (m *AppRepo) AppUpdate(app *appmodel.App, conn builder.Cond, columns ...str return m.repo.Where(conn).MustCols(columns...).Update(app) } -func (m *AppRepo) AppGet(app *appmodel.App, conn builder.Cond) (bool, error) { - return m.repo.Where(conn).Get(app) +func (m *AppRepo) AppFindOne(app *appmodel.App, conn builder.Cond, columns ...string) (*appmodel.App, error) { + has, err := m.repo.Where(conn).Get(app) + if !has { + return nil, sql.ErrNoRows + } + return app, err + } diff --git a/app/http/controllers/backend/app.go b/app/http/controllers/backend/app.go index a729f37..1b170fd 100644 --- a/app/http/controllers/backend/app.go +++ b/app/http/controllers/backend/app.go @@ -7,7 +7,7 @@ import ( "PaymentCenter/app/http/entities/backend" "PaymentCenter/app/models/appmodel" "PaymentCenter/app/services" - "PaymentCenter/app/utils/sm2" + "PaymentCenter/app/utils/encrypt/sm2" "github.com/ahmetb/go-linq/v3" "github.com/gin-gonic/gin" ) diff --git a/app/http/controllers/base.go b/app/http/controllers/base.go index e097b95..bd68940 100644 --- a/app/http/controllers/base.go +++ b/app/http/controllers/base.go @@ -230,3 +230,7 @@ func GetAdminUserIncludeUsers(c *gin.Context) string { } return "" } + +func ErrWithCode(c *gin.Context, code int) { + Error(c, code, errorcode.GetMsg(code, c.GetHeader("local"))) +} diff --git a/app/http/controllers/front/api.go b/app/http/controllers/front/api.go deleted file mode 100644 index 3d4ea9b..0000000 --- a/app/http/controllers/front/api.go +++ /dev/null @@ -1,10 +0,0 @@ -package front - -import ( - "PaymentCenter/app/http/controllers" - "github.com/gin-gonic/gin" -) - -func HelloHandler(c *gin.Context) { - controllers.Success(c, "aaaa") -} diff --git a/app/http/entities/front/pay.go b/app/http/entities/front/pay.go new file mode 100644 index 0000000..f3dca7a --- /dev/null +++ b/app/http/entities/front/pay.go @@ -0,0 +1,12 @@ +package front + +type PayCommonBody struct { + AppId int64 `json:"app_id" validate:"required"` + Timestamp int64 `json:"timestamp" validate:"required"` +} + +type PayWeb struct { + PayCommonBody + PayChannel int64 `json:"private_key_path"` + Delay int64 `json:"delay"` //延时时间 +} diff --git a/app/http/middlewares/base.go b/app/http/middlewares/base.go index 728350d..aa2b217 100644 --- a/app/http/middlewares/base.go +++ b/app/http/middlewares/base.go @@ -4,7 +4,10 @@ import ( "PaymentCenter/app/constants/common" "PaymentCenter/app/constants/errorcode" "PaymentCenter/app/http/controllers" + "PaymentCenter/app/http/entities" + "PaymentCenter/app/http/entities/front" "PaymentCenter/app/http/requestmapping" + "PaymentCenter/app/services" "PaymentCenter/app/utils" "PaymentCenter/config" "github.com/gin-gonic/gin" @@ -109,18 +112,52 @@ func ValidateRequest() gin.HandlerFunc { if handler == nil { utils.Log(c, "path", path) controllers.HandCodeRes(c, nil, errorcode.NotFound) - } else { - v := handler() - msg, err := controllers.GenRequest(c, v) - if err != nil { - utils.Log(c, "参数错误", "path=", path, "err=", err.Error(), "msg=", msg) - controllers.Error(c, errorcode.ParamError, msg...) - c.Abort() - } else { - c.Set("request", v) - c.Next() - } - + return } + v := handler() + msg, err := controllers.GenRequest(c, v) + if err != nil { + utils.Log(c, "参数错误", "path=", path, "err=", err.Error(), "msg=", msg) + controllers.Error(c, errorcode.ParamError, msg...) + c.Abort() + } + c.Set("request", v) + + c.Next() + } +} + +func ValidatePayRequest() gin.HandlerFunc { + return func(c *gin.Context) { + com, err := utils.SonicApiDataToStruct(controllers.GetRequest(c), &front.PayCommonBody{}) + if err != nil { + controllers.ErrWithCode(c, errorcode.ParamError) + } + comStruct := com.(*front.PayCommonBody) + //判断时间 + //now := time.Now().UnixNano() / 1000000 + //if comStruct.Timestamp > now || (config.GetConf().TimeOut != 0 && (now-comStruct.Timestamp) > config.GetConf().TimeOut) { + // controllers.ErrWithCode(c, errorcode.RequestTimeOut) + // return + //} + //获取app信息 + app, errCode := services.AppFindOne(entities.IdRequest{Id: comStruct.AppId}) + if errCode != errorcode.Success { + controllers.ErrWithCode(c, errCode) + return + } + //检查app可用性 + appCheck := services.NewAppCheck(app).Check() + if appCheck.GetCode() != errorcode.Success { + controllers.ErrWithCode(c, appCheck.GetCode()) + return + } + //检查白名单 + if !appCheck.IpCheck(c.ClientIP()) { + controllers.ErrWithCode(c, appCheck.GetCode()) + return + } + + c.Next() } } diff --git a/app/http/requestmapping/front.go b/app/http/requestmapping/front.go index a1a93aa..5660770 100644 --- a/app/http/requestmapping/front.go +++ b/app/http/requestmapping/front.go @@ -1,3 +1,10 @@ package requestmapping -var FrontRequestMap = map[string]func() interface{}{} +import ( + "PaymentCenter/app/constants/common" + "PaymentCenter/app/http/entities/front" +) + +var FrontRequestMap = map[string]func() interface{}{ + common.FRONT_V1 + "/pay/web": func() interface{} { return new(front.PayWeb) }, +} diff --git a/app/http/routes/route.go b/app/http/routes/route.go index 8c1f59e..f4366f9 100644 --- a/app/http/routes/route.go +++ b/app/http/routes/route.go @@ -4,8 +4,10 @@ package routes * 配置路由 */ import ( + "PaymentCenter/app/constants/common" "PaymentCenter/app/http/controllers" "PaymentCenter/app/http/controllers/front" + "PaymentCenter/app/http/controllers/backend" "PaymentCenter/app/http/middlewares" "PaymentCenter/app/http/trace" "PaymentCenter/app/utils/metric" @@ -14,8 +16,6 @@ import ( "github.com/gin-gonic/gin" "github.com/qit-team/snow-core/http/middleware" "github.com/qit-team/snow-core/log/logger" - "github.com/swaggo/gin-swagger" - "github.com/swaggo/gin-swagger/swaggerFiles" ) // api路由配置 @@ -44,11 +44,9 @@ func RegisterRoute(router *gin.Engine) { router.Use(middlewares.Cors()) router.NoRoute(controllers.Error404) - //api版本 - //v1 := router.Group("/v1", middlewares.ValidateRequest()) - //{ - // - //} + //router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) + v1 := router.Group(common.FRONT_V1, middlewares.ValidateRequest()) + { v1 := router.Group("/v1") { @@ -61,10 +59,8 @@ func RegisterRoute(router *gin.Engine) { } router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) + pay := v1.Group("pay", middlewares.ValidatePayRequest()) + pay.POST("web", backend.MerchantList) // 商户列表 + } - //router.GET("/hello", controllers.HelloHandler) - //router.GET("/create", controllers.HelloCreateHandler) - //router.GET("/update", controllers.UpdateHandler) - //router.GET("/delete", controllers.DeleteHandler) - //router.GET("/query", controllers.QueryHandler) } diff --git a/app/models/appmodel/app.go b/app/models/appmodel/app.go index b840778..b1b008a 100644 --- a/app/models/appmodel/app.go +++ b/app/models/appmodel/app.go @@ -15,10 +15,10 @@ var ( type App struct { Id int64 MerchantId int64 `xorm:"'merchant_id' bigint(20)"` - AppName string `xorm:"'app_name' varchar(128)"` - AppRemark string `xorm:"'app_remark' varchar(255)"` - Status int `xorm:"'status' int(11)"` - KeyType int `xorm:"'key_type' int(11)"` + AppName string `xorm:"'app_name' varchar(20)"` + AppRemark string `xorm:"'app_remark' varchar(200)"` + Status int32 `xorm:"'status' tinyint(2)"` + KeyType int32 `xorm:"'key_type' tinyint(2)"` PublicKey string `xorm:"'public_key' varchar(1024)"` PrivateKey string `xorm:"'private_key' varchar(1024)"` MerchantPublicKey string `xorm:"'merchant_public_key' varchar(1024)"` diff --git a/app/services/api_request_valid.go b/app/services/api_request_valid.go new file mode 100644 index 0000000..16cb09e --- /dev/null +++ b/app/services/api_request_valid.go @@ -0,0 +1,47 @@ +package services + +import ( + "PaymentCenter/app/constants/errorcode" + "PaymentCenter/app/constants/pojo" + "PaymentCenter/app/models/appmodel" + "PaymentCenter/app/utils" + "strings" +) + +type AppCheck struct { + App *appmodel.App + Code int +} + +func NewAppCheck(app *appmodel.App) *AppCheck { + return &AppCheck{ + App: app, + Code: errorcode.Success, + } +} + +func (a *AppCheck) IpCheck(ip string) bool { + if a.App.WhiteIp == "" { + return true + } + if !utils.ContainsString(strings.Split(a.App.WhiteIp, ","), ip) { + a.Code = errorcode.AppIpNotAllow + return false + } + return true +} + +func (a *AppCheck) Check() *AppCheck { + + if a.App.Status == pojo.STATUS_DISABLED { + a.Code = errorcode.AppDisabled + } + if a.App.DeleteTime.Location() == nil { + a.Code = errorcode.AppNotFound + } + return a +} + +func (a *AppCheck) GetCode() int { + return a.Code +} diff --git a/app/services/apicrypt/rsa.go b/app/services/apicrypt/rsa.go new file mode 100644 index 0000000..171271d --- /dev/null +++ b/app/services/apicrypt/rsa.go @@ -0,0 +1,17 @@ +package apicrypt + +import "PaymentCenter/app/models/appmodel" + +func NewRsa(app *appmodel.App) ApiDecrypt { + return &Rsa{ + App: app, + } +} + +func (r *Rsa) Encrypt(decryptData interface{}) (encryptData string, err error) { + return +} + +func (r *Rsa) Decrypt(encryptData string) (decryptData map[string]interface{}, err error) { + return +} diff --git a/app/services/apicrypt/sm2.go b/app/services/apicrypt/sm2.go new file mode 100644 index 0000000..2a18c77 --- /dev/null +++ b/app/services/apicrypt/sm2.go @@ -0,0 +1,9 @@ +package apicrypt + +func (r *SM2) Encrypt(decryptData interface{}) (encryptData string, err error) { + return +} + +func (r *SM2) Decrypt(encryptData string) (decryptData map[string]interface{}, err error) { + return +} diff --git a/app/services/apicrypt/sm4.go b/app/services/apicrypt/sm4.go new file mode 100644 index 0000000..4e16213 --- /dev/null +++ b/app/services/apicrypt/sm4.go @@ -0,0 +1,9 @@ +package apicrypt + +func (r *SM4) Encrypt(decryptData interface{}) (encryptData string, err error) { + return +} + +func (r *SM4) Decrypt(encryptData string) (decryptData map[string]interface{}, err error) { + return +} diff --git a/app/services/apicrypt/types.go b/app/services/apicrypt/types.go new file mode 100644 index 0000000..2e6e8ec --- /dev/null +++ b/app/services/apicrypt/types.go @@ -0,0 +1,22 @@ +package apicrypt + +import "PaymentCenter/app/models/appmodel" + +type ( + ApiDecrypt interface { + Encrypt(decryptData interface{}) (encryptData string, err error) + Decrypt(encryptData string) (decryptData map[string]interface{}, err error) + } + + Rsa struct { + App *appmodel.App + } + + SM2 struct { + App *appmodel.App + } + + SM4 struct { + App *appmodel.App + } +) diff --git a/app/services/app.go b/app/services/app.go index 2c67441..9b1211c 100644 --- a/app/services/app.go +++ b/app/services/app.go @@ -8,6 +8,7 @@ import ( "PaymentCenter/app/models/appmodel" "PaymentCenter/app/models/merchantmodel" "PaymentCenter/app/models/paychannelmodel" + "database/sql" "xorm.io/builder" ) @@ -64,6 +65,14 @@ func AppUpdate(app *appmodel.App) (code int) { } else { _, err = repo.AppUpdate(app, conn) } + if !has { + return errorcode.MerchantNotFound + } + + // 拼接查询条件 + uconn := builder.NewCond() + uconn = uconn.And(builder.Eq{"Id": App.Id}) + _, err = repo.AppUpdate(App, uconn, "app_remark") code = handErr(err) return @@ -82,18 +91,19 @@ func AppDelete(req entities.IdRequest) (code int) { return } -func AppGet(app *appmodel.App) (code int) { - repo := data.NewAppRepo(appmodel.GetInstance().GetDb()) +func AppFindOne(req entities.IdRequest, col ...string) (row *appmodel.App, code int) { + repo := data.NewAppRepo(paychannelmodel.GetInstance().GetDb()) + // 拼接查询条件 conn := builder.NewCond() - conn = conn.And(builder.Eq{"id": app.Id}) - has, err := repo.AppGet(app, conn) + conn = conn.And(builder.Eq{"Id": req.Id}) + m := appmodel.App{Id: req.Id} + row, err := repo.AppFindOne(&m, conn, col...) if err != nil { - return handErr(err) + if err == sql.ErrNoRows { + return nil, errorcode.AppNotFound + } + return row, errorcode.SystemError } - if !has { - return errorcode.AppNotFound - } - code = errorcode.Success - return + return row, errorcode.Success } diff --git a/app/utils/encrypt/rsa/rsa.go b/app/utils/encrypt/rsa/rsa.go new file mode 100644 index 0000000..f868e9d --- /dev/null +++ b/app/utils/encrypt/rsa/rsa.go @@ -0,0 +1,110 @@ +package rsa + +import ( + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "fmt" +) + +// parseRSAPublicKeyFromPEM 解析PEM编码的RSA公钥 +func parseRSAPublicKeyFromPEM(pemData []byte) (*rsa.PublicKey, error) { + block, _ := pem.Decode(pemData) + if block == nil || block.Type != "PUBLIC KEY" { + return nil, fmt.Errorf("failed to parse PEM block containing the RSA public key") + } + + pub, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + return nil, err + } + + switch pub := pub.(type) { + case *rsa.PublicKey: + return pub, nil + default: + return nil, fmt.Errorf("unknown public key type in PKIX wrapping") + } +} + +// encrypt 使用RSA公钥加密数据 +func Encrypt(publicKeyPEM string, plaintext []byte) ([]byte, error) { + // 将PEM编码的公钥转换为[]byte + pemData := []byte(publicKeyPEM) + + // 解析PEM数据以获取公钥 + pubKey, err := parseRSAPublicKeyFromPEM(pemData) + if err != nil { + return nil, err + } + + // 创建用于加密的随机填充 + label := []byte("") // OAEP标签,对于某些情况可能是非空的 + ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, plaintext, label) + if err != nil { + return nil, err + } + return ciphertext, nil +} + +// parseRSAPrivateKeyFromPEM 解析PEM编码的RSA私钥 +func parseRSAPrivateKeyFromPEM(pemData []byte) (*rsa.PrivateKey, error) { + block, _ := pem.Decode(pemData) + if block == nil || block.Type != "RSA PRIVATE KEY" { + return nil, fmt.Errorf("failed to parse PEM block containing the RSA private key") + } + + // 尝试使用PKCS#1 v1.5 + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + // 如果失败,尝试使用PKCS#8 + privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + + switch k := privInterface.(type) { + case *rsa.PrivateKey: + priv = k + default: + return nil, fmt.Errorf("unknown private key type in PKCS#8 wrapping") + } + } + + return priv, nil +} + +// decrypt 使用RSA私钥解密数据 +func Decrypt(privateKeyPEM string, encryptedDataBase64 string) ([]byte, error) { + // 将PEM编码的私钥转换为[]byte + pemData := []byte(privateKeyPEM) + + // 解析PEM数据以获取私钥 + privKey, err := parseRSAPrivateKeyFromPEM(pemData) + if err != nil { + return nil, err + } + + // 将Base64编码的加密数据解码为字节切片 + encryptedData, err := base64.StdEncoding.DecodeString(encryptedDataBase64) + if err != nil { + return nil, err + } + + // 根据你的加密方式选择合适的解密函数 + // 这里假设使用的是OAEP填充和SHA-256哈希函数 + label := []byte("") // OAEP标签,对于某些情况可能是非空的 + decrypted, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privKey, encryptedData, label) + if err != nil { + // 如果失败,可以尝试使用PKCS#1 v1.5填充 + decrypted, err = rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedData) + if err != nil { + return nil, err + } + } + + return decrypted, nil +} diff --git a/app/utils/encrypt/rsa/rsa_test.go b/app/utils/encrypt/rsa/rsa_test.go new file mode 100644 index 0000000..5425c75 --- /dev/null +++ b/app/utils/encrypt/rsa/rsa_test.go @@ -0,0 +1,42 @@ +package rsa + +import ( + "encoding/base64" + "fmt" + "testing" + "time" +) + +const ( + PRI = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCmjK6SPkrP03ssex5Dxn4KZeVm9rQoJMslru13GNgoGKJAq13xwUGl6lpGlhzM9IMzg0ldOO2a0SQPPjc0fLrDjIgHPfIT6H1hDGkZdPaF4D0OfiHGzlLwXq7FyyyGc2JXILsniMBXcCxNFhbW0jAaJyYrBJb3q84a5y5AtK3IC+eDV6Bj2J4HlQVGKgW9u2ic6Jxl23sacXY6iifi+KEuoXNCJrmYlgRWTaQovLmTCLkErkzxzG9DFRDWGoz25LthDPqcCSUmWEbJ+obwIGB4r2WCbFXvaeVBQORlyVRyNUvYMItjHBQIKinDWZ6y8KzA0YKOoxEfr0KfE8Uk4PQBAgMBAAECggEABTAX0PzelN4uyvTT0sMi/R0YRKPgepP40vtBsNvF10E7Lp4ClAupHpYFSrJq178xu1/2dVBXEGM9hw8GUQd7RCjuD3cFwcp/EKU+Zy6uQ38iZRTskEDa3bC+q3EXzuFXDxqOfIhai262UTlkATw0sjUwJRdkbMxoeWHkSNuH7UBVddxFL8Bq1DKaPzRCqQ8zlkMZHy8Xbf2b8rFoi1oPBoPjHyxCo33zcnSg5xntIoA5pkD6x4z5cAnU55aBoYUiRv7jmG+MVp1jpDvAmJLfUayVZNakgX1r74bMPsl9kpA7dVdgOlWrIkbJE1plVXXswBb8QKN0/Yx2vv/YASSi0QKBgQDaO9BkRjvht/lrsQEur1wXf5ITnsVWsqlUhYQKGHihzOj7e0rGO9QICM4eQZH9ssHfxEXhmEoFdkaqo3Fo47NI+yinpWm+KruwrRFkCGejlKZ4bhn9zWPb8L1qJbN4UD1c5jUNk1B0EEdnLRFg0/O7xm602bGilvY5x2nf0v95+QKBgQDDXyiiGNV7GO4h8OQYJwq0IqenPyIanRgYI3rw//tg147mhWcxT6ms6dMUh9nEXEFali2J1En+aVvx1Xn47CuGrRmZOLaGkw9ESFA/4ngYdea+xgttbKMXm0QwIwvATq2jxxrYEKmnr/+EUUWzIWioM1zQffAhVlkLFVnImquMSQKBgDe7qNfC/A4ELwWqubOTg0BZCxRJqvoePJJiWrs9Tql7rFB1Rz5jDx5SKVmew0r4OP0Nog8gFl9YumlfvlncNPBBfDt8SgoP3ckcGeHjJ5ymHPGKpMaliogj7ivKnw/t5g3wmMHzyksp0SJvZw3Ec22UGrfDFNOCHDXbUJWhzC75AoGBALbM6rAAnH65LNcFFeajYRh69HNAVyCfrFOpnvawDPzntAVs/MjeyNvJTH8BPXjE+UFREvrLbxBkdGsqWx3VnEQ+4pzCu8XfA4HYR33+4G/CoUwO8dJIu7DyzjJcGDqvYzjCqxNPQ+5qdqHPiW+56rq2lDlgHLaUnGwKZh+U2L5BAoGAeogtSQbnZaLQofSGcUOol2fyG24NU1JK3My+N1ypkSpD+y1KiFQeM5kg7UcJB6LBKZ/lRCKcjEMaxMyj57ETMkbRVKBLvsIL5QYolJLIHYqBul0AeFJ4K51SKK2Xk5rFvyuJKkJBux26WodtCXTnEzP1KRZGlSxJeN/V1yXjSEU=" + + PUB = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApoyukj5Kz9N7LHseQ8Z+CmXlZva0KCTLJa7tdxjYKBiiQKtd8cFBpepaRpYczPSDM4NJXTjtmtEkDz43NHy6w4yIBz3yE+h9YQxpGXT2heA9Dn4hxs5S8F6uxcsshnNiVyC7J4jAV3AsTRYW1tIwGicmKwSW96vOGucuQLStyAvng1egY9ieB5UFRioFvbtonOicZdt7GnF2Ooon4vihLqFzQia5mJYEVk2kKLy5kwi5BK5M8cxvQxUQ1hqM9uS7YQz6nAklJlhGyfqG8CBgeK9lgmxV72nlQUDkZclUcjVL2DCLYxwUCCopw1mesvCswNGCjqMRH69CnxPFJOD0AQIDAQAB" +) + +func TestRsaEncrypt(t *testing.T) { + fmt.Println(time.Now().UnixNano() / (1000000)) + //fmt.Printf("%s\n", encrypt()) +} + +func TestRsaDecrypt(t *testing.T) { + data := encrypt() + privateKeyPEM := `-----BEGIN RSA PRIVATE KEY----- +` + PRI + ` +-----END RSA PRIVATE KEY-----` + res, err := Decrypt(privateKeyPEM, data) + fmt.Println(string(res), err) +} + +func encrypt() string { + data := "{\"name\":\"张三\",\"sex\":1,\"is_human\":true}" + dataJson := []byte(data) + pub := `-----BEGIN PUBLIC KEY----- +` + PUB + ` +-----END PUBLIC KEY-----` + en, err := Encrypt(pub, dataJson) + if err != nil { + panic(err) + } + + return base64.StdEncoding.EncodeToString(en) +} diff --git a/app/utils/sm2/sm2.go b/app/utils/encrypt/sm2/sm2.go similarity index 87% rename from app/utils/sm2/sm2.go rename to app/utils/encrypt/sm2/sm2.go index b193b4f..6f9d745 100644 --- a/app/utils/sm2/sm2.go +++ b/app/utils/encrypt/sm2/sm2.go @@ -1,7 +1,6 @@ package sm2 import ( - "PaymentCenter/config" "crypto/rand" "encoding/base64" "encoding/hex" @@ -16,12 +15,21 @@ func GenerateSM2Key() (PublicKey string, PrivateKey string, err error) { // 生成私钥、公钥 privKey, err := sm2.GenerateKey(rand.Reader) if err != nil { - fmt.Println("生成密钥对失败:", err) + return "", "", err } return PublicKeyToString(&privKey.PublicKey), PrivateKeyToString(privKey), nil } +// GenerateKey 生成密钥对 +func GenerateKey() (string, string) { + pri, _ := sm2.GenerateKey(rand.Reader) + hexPri := pri.D.Text(16) + // 获取公钥 + publicKeyHex := PublicKeyToString(&pri.PublicKey) + return strings.ToUpper(hexPri), publicKeyHex +} + // PublicKeyToString 公钥sm2.PublicKey转字符串(与java中org.bouncycastle.crypto生成的公私钥完全互通使用) func PublicKeyToString(publicKey *sm2.PublicKey) string { xBytes := publicKey.X.Bytes() @@ -48,27 +56,27 @@ func PrivateKeyToString(privateKey *sm2.PrivateKey) string { return strings.ToUpper(hex.EncodeToString(privateKey.D.Bytes())) } -func SM2Decrypt(cipherText string) (string, error) { +func SM2Decrypt(cipherText, publicKey string, privateKey string) (string, error) { if cipherText == "" { return "", nil } decodedBytes, err := base64.StdEncoding.DecodeString(cipherText) if err != nil { - fmt.Println("解码错误:", err) + return "", nil } - decrypt, err := decryptLoc(config.GetConf().Sm2.PublicKey, config.GetConf().Sm2.PrivateKey, string(decodedBytes)) + decrypt, err := decryptLoc(publicKey, privateKey, string(decodedBytes)) if err != nil { return "", err } return decrypt, nil } -func SM2Encrypt(cipherText string) (string, error) { +func SM2Encrypt(cipherText string, privateKey string) (string, error) { if cipherText == "" { return "", nil } - decrypt, err := encryptLoc(config.GetConf().Sm2.PublicKey, cipherText) + decrypt, err := encryptLoc(privateKey, cipherText) if err != nil { return "", err } @@ -78,11 +86,11 @@ func SM2Encrypt(cipherText string) (string, error) { func encryptLoc(publicKeyStr, data string) (string, error) { publicKeyObj, err := StringToPublicKey(publicKeyStr) if err != nil { - fmt.Println(err) + return "", err } decrypt, err := sm2.Encrypt(publicKeyObj, []byte(data), rand.Reader, sm2.C1C2C3) if err != nil { - fmt.Println(err) + return "", err } resultStr := hex.EncodeToString(decrypt) return base64.StdEncoding.EncodeToString([]byte(resultStr)), nil @@ -103,7 +111,6 @@ func decryptLoc(publicKeyStr, privateKeyStr, cipherText string) (string, error) fmt.Println(err) } resultStr := string(decrypt) - fmt.Println("解密后的字符串:", resultStr) return resultStr, nil } diff --git a/app/utils/encrypt/sm2/sm2_test.go b/app/utils/encrypt/sm2/sm2_test.go new file mode 100644 index 0000000..e82a6f2 --- /dev/null +++ b/app/utils/encrypt/sm2/sm2_test.go @@ -0,0 +1,43 @@ +package sm2 + +import ( + "fmt" + "testing" +) + +const ( + SELF_PRI = "EA7CB6F907A96264D6763F8C46AB96B476538D2ABC880A459E10BE5A1C30013D" + + SELF_PUB = "04363DF574D4FE34EE58FB8A3F7CB08E6CA5EBB3B7335CBAE10A2900551F6450AB3AD25DBC0A76EFA9E6D44D2C51E3027483F7BFD09996457888BAFD1AF673817F" +) + +func TestGenerateSM2KeyPair(t *testing.T) { + // Generate a new SM2 key pair + privateKey, publicKey := GenerateKey() + + // Print the private and public keys + fmt.Printf("Private Key: %s\n", privateKey) + fmt.Printf("Public Key: %s", publicKey) +} + +func TestSM2Encrypt(t *testing.T) { + t.Log(encrypt()) +} + +func TestSM2Decrypt(t *testing.T) { + en := encrypt() + decrypt, err := SM2Decrypt(en, SELF_PUB, SELF_PRI) + if err != nil { + panic(err) + } + t.Log(decrypt) +} + +func encrypt() string { + data := "{\"name\":\"张三\",\"sex\":1,\"is_human\":true}" + en, err := SM2Encrypt(data, SELF_PUB) + if err != nil { + panic(err) + } + return en +} diff --git a/app/utils/encrypt/sm4/internal/sm2/p256.go b/app/utils/encrypt/sm4/internal/sm2/p256.go new file mode 100644 index 0000000..1ad2712 --- /dev/null +++ b/app/utils/encrypt/sm4/internal/sm2/p256.go @@ -0,0 +1,1157 @@ +/* +Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package sm2 + +import ( + "crypto/elliptic" + "math/big" + "sync" +) + +type sm2P256Curve struct { + RInverse *big.Int + *elliptic.CurveParams + a, b, gx, gy sm2P256FieldElement +} + +var initonce sync.Once +var sm2P256 sm2P256Curve + +type sm2P256FieldElement [9]uint32 +type sm2P256LargeFieldElement [17]uint64 + +const ( + bottom28Bits = 0xFFFFFFF + bottom29Bits = 0x1FFFFFFF +) + +func initP256Sm2() { + sm2P256.CurveParams = &elliptic.CurveParams{Name: "SM2-P-256"} // sm2 + A, _ := new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16) + //SM2椭 椭 圆 曲 线 公 钥 密 码 算 法 推 荐 曲 线 参 数 + sm2P256.P, _ = new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16) + sm2P256.N, _ = new(big.Int).SetString("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16) + sm2P256.B, _ = new(big.Int).SetString("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16) + sm2P256.Gx, _ = new(big.Int).SetString("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16) + sm2P256.Gy, _ = new(big.Int).SetString("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16) + sm2P256.RInverse, _ = new(big.Int).SetString("7ffffffd80000002fffffffe000000017ffffffe800000037ffffffc80000002", 16) + sm2P256.BitSize = 256 + sm2P256FromBig(&sm2P256.a, A) + sm2P256FromBig(&sm2P256.gx, sm2P256.Gx) + sm2P256FromBig(&sm2P256.gy, sm2P256.Gy) + sm2P256FromBig(&sm2P256.b, sm2P256.B) +} + +func P256Sm2() elliptic.Curve { + initonce.Do(initP256Sm2) + return sm2P256 +} + +func (curve sm2P256Curve) Params() *elliptic.CurveParams { + return sm2P256.CurveParams +} + +// y^2 = x^3 + ax + b +func (curve sm2P256Curve) IsOnCurve(X, Y *big.Int) bool { + var a, x, y, y2, x3 sm2P256FieldElement + + sm2P256FromBig(&x, X) + sm2P256FromBig(&y, Y) + + sm2P256Square(&x3, &x) // x3 = x ^ 2 + sm2P256Mul(&x3, &x3, &x) // x3 = x ^ 2 * x + sm2P256Mul(&a, &curve.a, &x) // a = a * x + sm2P256Add(&x3, &x3, &a) + sm2P256Add(&x3, &x3, &curve.b) + + sm2P256Square(&y2, &y) // y2 = y ^ 2 + return sm2P256ToBig(&x3).Cmp(sm2P256ToBig(&y2)) == 0 +} + +func zForAffine(x, y *big.Int) *big.Int { + z := new(big.Int) + if x.Sign() != 0 || y.Sign() != 0 { + z.SetInt64(1) + } + return z +} + +func (curve sm2P256Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { + var X1, Y1, Z1, X2, Y2, Z2, X3, Y3, Z3 sm2P256FieldElement + + z1 := zForAffine(x1, y1) + z2 := zForAffine(x2, y2) + sm2P256FromBig(&X1, x1) + sm2P256FromBig(&Y1, y1) + sm2P256FromBig(&Z1, z1) + sm2P256FromBig(&X2, x2) + sm2P256FromBig(&Y2, y2) + sm2P256FromBig(&Z2, z2) + sm2P256PointAdd(&X1, &Y1, &Z1, &X2, &Y2, &Z2, &X3, &Y3, &Z3) + return sm2P256ToAffine(&X3, &Y3, &Z3) +} + +func (curve sm2P256Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { + var X1, Y1, Z1 sm2P256FieldElement + + z1 := zForAffine(x1, y1) + sm2P256FromBig(&X1, x1) + sm2P256FromBig(&Y1, y1) + sm2P256FromBig(&Z1, z1) + sm2P256PointDouble(&X1, &Y1, &Z1, &X1, &Y1, &Z1) + return sm2P256ToAffine(&X1, &Y1, &Z1) +} + +func (curve sm2P256Curve) ScalarMult(x1, y1 *big.Int, k []byte) (*big.Int, *big.Int) { + var X, Y, Z, X1, Y1 sm2P256FieldElement + sm2P256FromBig(&X1, x1) + sm2P256FromBig(&Y1, y1) + scalar := sm2GenrateWNaf(k) + scalarReversed := WNafReversed(scalar) + sm2P256ScalarMult(&X, &Y, &Z, &X1, &Y1, scalarReversed) + return sm2P256ToAffine(&X, &Y, &Z) +} + +func (curve sm2P256Curve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { + var scalarReversed [32]byte + var X, Y, Z sm2P256FieldElement + + sm2P256GetScalar(&scalarReversed, k) + sm2P256ScalarBaseMult(&X, &Y, &Z, &scalarReversed) + return sm2P256ToAffine(&X, &Y, &Z) +} + +var sm2P256Precomputed = [9 * 2 * 15 * 2]uint32{ + 0x830053d, 0x328990f, 0x6c04fe1, 0xc0f72e5, 0x1e19f3c, 0x666b093, 0x175a87b, 0xec38276, 0x222cf4b, + 0x185a1bba, 0x354e593, 0x1295fac1, 0xf2bc469, 0x47c60fa, 0xc19b8a9, 0xf63533e, 0x903ae6b, 0xc79acba, + 0x15b061a4, 0x33e020b, 0xdffb34b, 0xfcf2c8, 0x16582e08, 0x262f203, 0xfb34381, 0xa55452, 0x604f0ff, + 0x41f1f90, 0xd64ced2, 0xee377bf, 0x75f05f0, 0x189467ae, 0xe2244e, 0x1e7700e8, 0x3fbc464, 0x9612d2e, + 0x1341b3b8, 0xee84e23, 0x1edfa5b4, 0x14e6030, 0x19e87be9, 0x92f533c, 0x1665d96c, 0x226653e, 0xa238d3e, + 0xf5c62c, 0x95bb7a, 0x1f0e5a41, 0x28789c3, 0x1f251d23, 0x8726609, 0xe918910, 0x8096848, 0xf63d028, + 0x152296a1, 0x9f561a8, 0x14d376fb, 0x898788a, 0x61a95fb, 0xa59466d, 0x159a003d, 0x1ad1698, 0x93cca08, + 0x1b314662, 0x706e006, 0x11ce1e30, 0x97b710, 0x172fbc0d, 0x8f50158, 0x11c7ffe7, 0xd182cce, 0xc6ad9e8, + 0x12ea31b2, 0xc4e4f38, 0x175b0d96, 0xec06337, 0x75a9c12, 0xb001fdf, 0x93e82f5, 0x34607de, 0xb8035ed, + 0x17f97924, 0x75cf9e6, 0xdceaedd, 0x2529924, 0x1a10c5ff, 0xb1a54dc, 0x19464d8, 0x2d1997, 0xde6a110, + 0x1e276ee5, 0x95c510c, 0x1aca7c7a, 0xfe48aca, 0x121ad4d9, 0xe4132c6, 0x8239b9d, 0x40ea9cd, 0x816c7b, + 0x632d7a4, 0xa679813, 0x5911fcf, 0x82b0f7c, 0x57b0ad5, 0xbef65, 0xd541365, 0x7f9921f, 0xc62e7a, + 0x3f4b32d, 0x58e50e1, 0x6427aed, 0xdcdda67, 0xe8c2d3e, 0x6aa54a4, 0x18df4c35, 0x49a6a8e, 0x3cd3d0c, + 0xd7adf2, 0xcbca97, 0x1bda5f2d, 0x3258579, 0x606b1e6, 0x6fc1b5b, 0x1ac27317, 0x503ca16, 0xa677435, + 0x57bc73, 0x3992a42, 0xbab987b, 0xfab25eb, 0x128912a4, 0x90a1dc4, 0x1402d591, 0x9ffbcfc, 0xaa48856, + 0x7a7c2dc, 0xcefd08a, 0x1b29bda6, 0xa785641, 0x16462d8c, 0x76241b7, 0x79b6c3b, 0x204ae18, 0xf41212b, + 0x1f567a4d, 0xd6ce6db, 0xedf1784, 0x111df34, 0x85d7955, 0x55fc189, 0x1b7ae265, 0xf9281ac, 0xded7740, + 0xf19468b, 0x83763bb, 0x8ff7234, 0x3da7df8, 0x9590ac3, 0xdc96f2a, 0x16e44896, 0x7931009, 0x99d5acc, + 0x10f7b842, 0xaef5e84, 0xc0310d7, 0xdebac2c, 0x2a7b137, 0x4342344, 0x19633649, 0x3a10624, 0x4b4cb56, + 0x1d809c59, 0xac007f, 0x1f0f4bcd, 0xa1ab06e, 0xc5042cf, 0x82c0c77, 0x76c7563, 0x22c30f3, 0x3bf1568, + 0x7a895be, 0xfcca554, 0x12e90e4c, 0x7b4ab5f, 0x13aeb76b, 0x5887e2c, 0x1d7fe1e3, 0x908c8e3, 0x95800ee, + 0xb36bd54, 0xf08905d, 0x4e73ae8, 0xf5a7e48, 0xa67cb0, 0x50e1067, 0x1b944a0a, 0xf29c83a, 0xb23cfb9, + 0xbe1db1, 0x54de6e8, 0xd4707f2, 0x8ebcc2d, 0x2c77056, 0x1568ce4, 0x15fcc849, 0x4069712, 0xe2ed85f, + 0x2c5ff09, 0x42a6929, 0x628e7ea, 0xbd5b355, 0xaf0bd79, 0xaa03699, 0xdb99816, 0x4379cef, 0x81d57b, + 0x11237f01, 0xe2a820b, 0xfd53b95, 0x6beb5ee, 0x1aeb790c, 0xe470d53, 0x2c2cfee, 0x1c1d8d8, 0xa520fc4, + 0x1518e034, 0xa584dd4, 0x29e572b, 0xd4594fc, 0x141a8f6f, 0x8dfccf3, 0x5d20ba3, 0x2eb60c3, 0x9f16eb0, + 0x11cec356, 0xf039f84, 0x1b0990c1, 0xc91e526, 0x10b65bae, 0xf0616e8, 0x173fa3ff, 0xec8ccf9, 0xbe32790, + 0x11da3e79, 0xe2f35c7, 0x908875c, 0xdacf7bd, 0x538c165, 0x8d1487f, 0x7c31aed, 0x21af228, 0x7e1689d, + 0xdfc23ca, 0x24f15dc, 0x25ef3c4, 0x35248cd, 0x99a0f43, 0xa4b6ecc, 0xd066b3, 0x2481152, 0x37a7688, + 0x15a444b6, 0xb62300c, 0x4b841b, 0xa655e79, 0xd53226d, 0xbeb348a, 0x127f3c2, 0xb989247, 0x71a277d, + 0x19e9dfcb, 0xb8f92d0, 0xe2d226c, 0x390a8b0, 0x183cc462, 0x7bd8167, 0x1f32a552, 0x5e02db4, 0xa146ee9, + 0x1a003957, 0x1c95f61, 0x1eeec155, 0x26f811f, 0xf9596ba, 0x3082bfb, 0x96df083, 0x3e3a289, 0x7e2d8be, + 0x157a63e0, 0x99b8941, 0x1da7d345, 0xcc6cd0, 0x10beed9a, 0x48e83c0, 0x13aa2e25, 0x7cad710, 0x4029988, + 0x13dfa9dd, 0xb94f884, 0x1f4adfef, 0xb88543, 0x16f5f8dc, 0xa6a67f4, 0x14e274e2, 0x5e56cf4, 0x2f24ef, + 0x1e9ef967, 0xfe09bad, 0xfe079b3, 0xcc0ae9e, 0xb3edf6d, 0x3e961bc, 0x130d7831, 0x31043d6, 0xba986f9, + 0x1d28055, 0x65240ca, 0x4971fa3, 0x81b17f8, 0x11ec34a5, 0x8366ddc, 0x1471809, 0xfa5f1c6, 0xc911e15, + 0x8849491, 0xcf4c2e2, 0x14471b91, 0x39f75be, 0x445c21e, 0xf1585e9, 0x72cc11f, 0x4c79f0c, 0xe5522e1, + 0x1874c1ee, 0x4444211, 0x7914884, 0x3d1b133, 0x25ba3c, 0x4194f65, 0x1c0457ef, 0xac4899d, 0xe1fa66c, + 0x130a7918, 0x9b8d312, 0x4b1c5c8, 0x61ccac3, 0x18c8aa6f, 0xe93cb0a, 0xdccb12c, 0xde10825, 0x969737d, + 0xf58c0c3, 0x7cee6a9, 0xc2c329a, 0xc7f9ed9, 0x107b3981, 0x696a40e, 0x152847ff, 0x4d88754, 0xb141f47, + 0x5a16ffe, 0x3a7870a, 0x18667659, 0x3b72b03, 0xb1c9435, 0x9285394, 0xa00005a, 0x37506c, 0x2edc0bb, + 0x19afe392, 0xeb39cac, 0x177ef286, 0xdf87197, 0x19f844ed, 0x31fe8, 0x15f9bfd, 0x80dbec, 0x342e96e, + 0x497aced, 0xe88e909, 0x1f5fa9ba, 0x530a6ee, 0x1ef4e3f1, 0x69ffd12, 0x583006d, 0x2ecc9b1, 0x362db70, + 0x18c7bdc5, 0xf4bb3c5, 0x1c90b957, 0xf067c09, 0x9768f2b, 0xf73566a, 0x1939a900, 0x198c38a, 0x202a2a1, + 0x4bbf5a6, 0x4e265bc, 0x1f44b6e7, 0x185ca49, 0xa39e81b, 0x24aff5b, 0x4acc9c2, 0x638bdd3, 0xb65b2a8, + 0x6def8be, 0xb94537a, 0x10b81dee, 0xe00ec55, 0x2f2cdf7, 0xc20622d, 0x2d20f36, 0xe03c8c9, 0x898ea76, + 0x8e3921b, 0x8905bff, 0x1e94b6c8, 0xee7ad86, 0x154797f2, 0xa620863, 0x3fbd0d9, 0x1f3caab, 0x30c24bd, + 0x19d3892f, 0x59c17a2, 0x1ab4b0ae, 0xf8714ee, 0x90c4098, 0xa9c800d, 0x1910236b, 0xea808d3, 0x9ae2f31, + 0x1a15ad64, 0xa48c8d1, 0x184635a4, 0xb725ef1, 0x11921dcc, 0x3f866df, 0x16c27568, 0xbdf580a, 0xb08f55c, + 0x186ee1c, 0xb1627fa, 0x34e82f6, 0x933837e, 0xf311be5, 0xfedb03b, 0x167f72cd, 0xa5469c0, 0x9c82531, + 0xb92a24b, 0x14fdc8b, 0x141980d1, 0xbdc3a49, 0x7e02bb1, 0xaf4e6dd, 0x106d99e1, 0xd4616fc, 0x93c2717, + 0x1c0a0507, 0xc6d5fed, 0x9a03d8b, 0xa1d22b0, 0x127853e3, 0xc4ac6b8, 0x1a048cf7, 0x9afb72c, 0x65d485d, + 0x72d5998, 0xe9fa744, 0xe49e82c, 0x253cf80, 0x5f777ce, 0xa3799a5, 0x17270cbb, 0xc1d1ef0, 0xdf74977, + 0x114cb859, 0xfa8e037, 0xb8f3fe5, 0xc734cc6, 0x70d3d61, 0xeadac62, 0x12093dd0, 0x9add67d, 0x87200d6, + 0x175bcbb, 0xb29b49f, 0x1806b79c, 0x12fb61f, 0x170b3a10, 0x3aaf1cf, 0xa224085, 0x79d26af, 0x97759e2, + 0x92e19f1, 0xb32714d, 0x1f00d9f1, 0xc728619, 0x9e6f627, 0xe745e24, 0x18ea4ace, 0xfc60a41, 0x125f5b2, + 0xc3cf512, 0x39ed486, 0xf4d15fa, 0xf9167fd, 0x1c1f5dd5, 0xc21a53e, 0x1897930, 0x957a112, 0x21059a0, + 0x1f9e3ddc, 0xa4dfced, 0x8427f6f, 0x726fbe7, 0x1ea658f8, 0x2fdcd4c, 0x17e9b66f, 0xb2e7c2e, 0x39923bf, + 0x1bae104, 0x3973ce5, 0xc6f264c, 0x3511b84, 0x124195d7, 0x11996bd, 0x20be23d, 0xdc437c4, 0x4b4f16b, + 0x11902a0, 0x6c29cc9, 0x1d5ffbe6, 0xdb0b4c7, 0x10144c14, 0x2f2b719, 0x301189, 0x2343336, 0xa0bf2ac, +} + +func sm2P256GetScalar(b *[32]byte, a []byte) { + var scalarBytes []byte + + n := new(big.Int).SetBytes(a) + if n.Cmp(sm2P256.N) >= 0 { + n.Mod(n, sm2P256.N) + scalarBytes = n.Bytes() + } else { + scalarBytes = a + } + for i, v := range scalarBytes { + b[len(scalarBytes)-(1+i)] = v + } +} + +func sm2P256PointAddMixed(xOut, yOut, zOut, x1, y1, z1, x2, y2 *sm2P256FieldElement) { + var z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp sm2P256FieldElement + + sm2P256Square(&z1z1, z1) + sm2P256Add(&tmp, z1, z1) + + sm2P256Mul(&u2, x2, &z1z1) + sm2P256Mul(&z1z1z1, z1, &z1z1) + sm2P256Mul(&s2, y2, &z1z1z1) + sm2P256Sub(&h, &u2, x1) + sm2P256Add(&i, &h, &h) + sm2P256Square(&i, &i) + sm2P256Mul(&j, &h, &i) + sm2P256Sub(&r, &s2, y1) + sm2P256Add(&r, &r, &r) + sm2P256Mul(&v, x1, &i) + + sm2P256Mul(zOut, &tmp, &h) + sm2P256Square(&rr, &r) + sm2P256Sub(xOut, &rr, &j) + sm2P256Sub(xOut, xOut, &v) + sm2P256Sub(xOut, xOut, &v) + + sm2P256Sub(&tmp, &v, xOut) + sm2P256Mul(yOut, &tmp, &r) + sm2P256Mul(&tmp, y1, &j) + sm2P256Sub(yOut, yOut, &tmp) + sm2P256Sub(yOut, yOut, &tmp) +} + +// sm2P256CopyConditional sets out=in if mask = 0xffffffff in constant time. +// +// On entry: mask is either 0 or 0xffffffff. +func sm2P256CopyConditional(out, in *sm2P256FieldElement, mask uint32) { + for i := 0; i < 9; i++ { + tmp := mask & (in[i] ^ out[i]) + out[i] ^= tmp + } +} + +// sm2P256SelectAffinePoint sets {out_x,out_y} to the index'th entry of table. +// On entry: index < 16, table[0] must be zero. +func sm2P256SelectAffinePoint(xOut, yOut *sm2P256FieldElement, table []uint32, index uint32) { + for i := range xOut { + xOut[i] = 0 + } + for i := range yOut { + yOut[i] = 0 + } + + for i := uint32(1); i < 16; i++ { + mask := i ^ index + mask |= mask >> 2 + mask |= mask >> 1 + mask &= 1 + mask-- + for j := range xOut { + xOut[j] |= table[0] & mask + table = table[1:] + } + for j := range yOut { + yOut[j] |= table[0] & mask + table = table[1:] + } + } +} + +// sm2P256SelectJacobianPoint sets {out_x,out_y,out_z} to the index'th entry of +// table. +// On entry: index < 16, table[0] must be zero. +func sm2P256SelectJacobianPoint(xOut, yOut, zOut *sm2P256FieldElement, table *[16][3]sm2P256FieldElement, index uint32) { + for i := range xOut { + xOut[i] = 0 + } + for i := range yOut { + yOut[i] = 0 + } + for i := range zOut { + zOut[i] = 0 + } + + // The implicit value at index 0 is all zero. We don't need to perform that + // iteration of the loop because we already set out_* to zero. + for i := uint32(1); i < 16; i++ { + mask := i ^ index + mask |= mask >> 2 + mask |= mask >> 1 + mask &= 1 + mask-- + for j := range xOut { + xOut[j] |= table[i][0][j] & mask + } + for j := range yOut { + yOut[j] |= table[i][1][j] & mask + } + for j := range zOut { + zOut[j] |= table[i][2][j] & mask + } + } +} + +// sm2P256GetBit returns the bit'th bit of scalar. +func sm2P256GetBit(scalar *[32]uint8, bit uint) uint32 { + return uint32(((scalar[bit>>3]) >> (bit & 7)) & 1) +} + +// sm2P256ScalarBaseMult sets {xOut,yOut,zOut} = scalar*G where scalar is a +// little-endian number. Note that the value of scalar must be less than the +// order of the group. +func sm2P256ScalarBaseMult(xOut, yOut, zOut *sm2P256FieldElement, scalar *[32]uint8) { + nIsInfinityMask := ^uint32(0) + var px, py, tx, ty, tz sm2P256FieldElement + var pIsNoninfiniteMask, mask, tableOffset uint32 + + for i := range xOut { + xOut[i] = 0 + } + for i := range yOut { + yOut[i] = 0 + } + for i := range zOut { + zOut[i] = 0 + } + + // The loop adds bits at positions 0, 64, 128 and 192, followed by + // positions 32,96,160 and 224 and does this 32 times. + for i := uint(0); i < 32; i++ { + if i != 0 { + sm2P256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) + } + tableOffset = 0 + for j := uint(0); j <= 32; j += 32 { + bit0 := sm2P256GetBit(scalar, 31-i+j) + bit1 := sm2P256GetBit(scalar, 95-i+j) + bit2 := sm2P256GetBit(scalar, 159-i+j) + bit3 := sm2P256GetBit(scalar, 223-i+j) + index := bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3) + + sm2P256SelectAffinePoint(&px, &py, sm2P256Precomputed[tableOffset:], index) + tableOffset += 30 * 9 + + // Since scalar is less than the order of the group, we know that + // {xOut,yOut,zOut} != {px,py,1}, unless both are zero, which we handle + // below. + sm2P256PointAddMixed(&tx, &ty, &tz, xOut, yOut, zOut, &px, &py) + // The result of pointAddMixed is incorrect if {xOut,yOut,zOut} is zero + // (a.k.a. the point at infinity). We handle that situation by + // copying the point from the table. + sm2P256CopyConditional(xOut, &px, nIsInfinityMask) + sm2P256CopyConditional(yOut, &py, nIsInfinityMask) + sm2P256CopyConditional(zOut, &sm2P256Factor[1], nIsInfinityMask) + + // Equally, the result is also wrong if the point from the table is + // zero, which happens when the index is zero. We handle that by + // only copying from {tx,ty,tz} to {xOut,yOut,zOut} if index != 0. + pIsNoninfiniteMask = nonZeroToAllOnes(index) + mask = pIsNoninfiniteMask & ^nIsInfinityMask + sm2P256CopyConditional(xOut, &tx, mask) + sm2P256CopyConditional(yOut, &ty, mask) + sm2P256CopyConditional(zOut, &tz, mask) + // If p was not zero, then n is now non-zero. + nIsInfinityMask &^= pIsNoninfiniteMask + } + } +} + +func sm2P256PointToAffine(xOut, yOut, x, y, z *sm2P256FieldElement) { + var zInv, zInvSq sm2P256FieldElement + + zz := sm2P256ToBig(z) + zz.ModInverse(zz, sm2P256.P) + sm2P256FromBig(&zInv, zz) + + sm2P256Square(&zInvSq, &zInv) + sm2P256Mul(xOut, x, &zInvSq) + sm2P256Mul(&zInv, &zInv, &zInvSq) + sm2P256Mul(yOut, y, &zInv) +} + +func sm2P256ToAffine(x, y, z *sm2P256FieldElement) (xOut, yOut *big.Int) { + var xx, yy sm2P256FieldElement + + sm2P256PointToAffine(&xx, &yy, x, y, z) + return sm2P256ToBig(&xx), sm2P256ToBig(&yy) +} + +var sm2P256Factor = []sm2P256FieldElement{ + sm2P256FieldElement{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, + sm2P256FieldElement{0x2, 0x0, 0x1FFFFF00, 0x7FF, 0x0, 0x0, 0x0, 0x2000000, 0x0}, + sm2P256FieldElement{0x4, 0x0, 0x1FFFFE00, 0xFFF, 0x0, 0x0, 0x0, 0x4000000, 0x0}, + sm2P256FieldElement{0x6, 0x0, 0x1FFFFD00, 0x17FF, 0x0, 0x0, 0x0, 0x6000000, 0x0}, + sm2P256FieldElement{0x8, 0x0, 0x1FFFFC00, 0x1FFF, 0x0, 0x0, 0x0, 0x8000000, 0x0}, + sm2P256FieldElement{0xA, 0x0, 0x1FFFFB00, 0x27FF, 0x0, 0x0, 0x0, 0xA000000, 0x0}, + sm2P256FieldElement{0xC, 0x0, 0x1FFFFA00, 0x2FFF, 0x0, 0x0, 0x0, 0xC000000, 0x0}, + sm2P256FieldElement{0xE, 0x0, 0x1FFFF900, 0x37FF, 0x0, 0x0, 0x0, 0xE000000, 0x0}, + sm2P256FieldElement{0x10, 0x0, 0x1FFFF800, 0x3FFF, 0x0, 0x0, 0x0, 0x0, 0x01}, +} + +func sm2P256Scalar(b *sm2P256FieldElement, a int) { + sm2P256Mul(b, b, &sm2P256Factor[a]) +} + +// (x3, y3, z3) = (x1, y1, z1) + (x2, y2, z2) +func sm2P256PointAdd(x1, y1, z1, x2, y2, z2, x3, y3, z3 *sm2P256FieldElement) { + var u1, u2, z22, z12, z23, z13, s1, s2, h, h2, r, r2, tm sm2P256FieldElement + + if sm2P256ToBig(z1).Sign() == 0 { + sm2P256Dup(x3, x2) + sm2P256Dup(y3, y2) + sm2P256Dup(z3, z2) + return + } + + if sm2P256ToBig(z2).Sign() == 0 { + sm2P256Dup(x3, x1) + sm2P256Dup(y3, y1) + sm2P256Dup(z3, z1) + return + } + + sm2P256Square(&z12, z1) // z12 = z1 ^ 2 + sm2P256Square(&z22, z2) // z22 = z2 ^ 2 + + sm2P256Mul(&z13, &z12, z1) // z13 = z1 ^ 3 + sm2P256Mul(&z23, &z22, z2) // z23 = z2 ^ 3 + + sm2P256Mul(&u1, x1, &z22) // u1 = x1 * z2 ^ 2 + sm2P256Mul(&u2, x2, &z12) // u2 = x2 * z1 ^ 2 + + sm2P256Mul(&s1, y1, &z23) // s1 = y1 * z2 ^ 3 + sm2P256Mul(&s2, y2, &z13) // s2 = y2 * z1 ^ 3 + + if sm2P256ToBig(&u1).Cmp(sm2P256ToBig(&u2)) == 0 && + sm2P256ToBig(&s1).Cmp(sm2P256ToBig(&s2)) == 0 { + sm2P256PointDouble(x1, y1, z1, x1, y1, z1) + } + + sm2P256Sub(&h, &u2, &u1) // h = u2 - u1 + sm2P256Sub(&r, &s2, &s1) // r = s2 - s1 + + sm2P256Square(&r2, &r) // r2 = r ^ 2 + sm2P256Square(&h2, &h) // h2 = h ^ 2 + + sm2P256Mul(&tm, &h2, &h) // tm = h ^ 3 + sm2P256Sub(x3, &r2, &tm) + sm2P256Mul(&tm, &u1, &h2) + sm2P256Scalar(&tm, 2) // tm = 2 * (u1 * h ^ 2) + sm2P256Sub(x3, x3, &tm) // x3 = r ^ 2 - h ^ 3 - 2 * u1 * h ^ 2 + + sm2P256Mul(&tm, &u1, &h2) // tm = u1 * h ^ 2 + sm2P256Sub(&tm, &tm, x3) // tm = u1 * h ^ 2 - x3 + sm2P256Mul(y3, &r, &tm) + sm2P256Mul(&tm, &h2, &h) // tm = h ^ 3 + sm2P256Mul(&tm, &tm, &s1) // tm = s1 * h ^ 3 + sm2P256Sub(y3, y3, &tm) // y3 = r * (u1 * h ^ 2 - x3) - s1 * h ^ 3 + + sm2P256Mul(z3, z1, z2) + sm2P256Mul(z3, z3, &h) // z3 = z1 * z3 * h +} + +// (x3, y3, z3) = (x1, y1, z1)- (x2, y2, z2) +func sm2P256PointSub(x1, y1, z1, x2, y2, z2, x3, y3, z3 *sm2P256FieldElement) { + var u1, u2, z22, z12, z23, z13, s1, s2, h, h2, r, r2, tm sm2P256FieldElement + y := sm2P256ToBig(y2) + zero := new(big.Int).SetInt64(0) + y.Sub(zero, y) + sm2P256FromBig(y2, y) + + if sm2P256ToBig(z1).Sign() == 0 { + sm2P256Dup(x3, x2) + sm2P256Dup(y3, y2) + sm2P256Dup(z3, z2) + return + } + + if sm2P256ToBig(z2).Sign() == 0 { + sm2P256Dup(x3, x1) + sm2P256Dup(y3, y1) + sm2P256Dup(z3, z1) + return + } + + sm2P256Square(&z12, z1) // z12 = z1 ^ 2 + sm2P256Square(&z22, z2) // z22 = z2 ^ 2 + + sm2P256Mul(&z13, &z12, z1) // z13 = z1 ^ 3 + sm2P256Mul(&z23, &z22, z2) // z23 = z2 ^ 3 + + sm2P256Mul(&u1, x1, &z22) // u1 = x1 * z2 ^ 2 + sm2P256Mul(&u2, x2, &z12) // u2 = x2 * z1 ^ 2 + + sm2P256Mul(&s1, y1, &z23) // s1 = y1 * z2 ^ 3 + sm2P256Mul(&s2, y2, &z13) // s2 = y2 * z1 ^ 3 + + if sm2P256ToBig(&u1).Cmp(sm2P256ToBig(&u2)) == 0 && + sm2P256ToBig(&s1).Cmp(sm2P256ToBig(&s2)) == 0 { + sm2P256PointDouble(x1, y1, z1, x1, y1, z1) + } + + sm2P256Sub(&h, &u2, &u1) // h = u2 - u1 + sm2P256Sub(&r, &s2, &s1) // r = s2 - s1 + + sm2P256Square(&r2, &r) // r2 = r ^ 2 + sm2P256Square(&h2, &h) // h2 = h ^ 2 + + sm2P256Mul(&tm, &h2, &h) // tm = h ^ 3 + sm2P256Sub(x3, &r2, &tm) + sm2P256Mul(&tm, &u1, &h2) + sm2P256Scalar(&tm, 2) // tm = 2 * (u1 * h ^ 2) + sm2P256Sub(x3, x3, &tm) // x3 = r ^ 2 - h ^ 3 - 2 * u1 * h ^ 2 + + sm2P256Mul(&tm, &u1, &h2) // tm = u1 * h ^ 2 + sm2P256Sub(&tm, &tm, x3) // tm = u1 * h ^ 2 - x3 + sm2P256Mul(y3, &r, &tm) + sm2P256Mul(&tm, &h2, &h) // tm = h ^ 3 + sm2P256Mul(&tm, &tm, &s1) // tm = s1 * h ^ 3 + sm2P256Sub(y3, y3, &tm) // y3 = r * (u1 * h ^ 2 - x3) - s1 * h ^ 3 + + sm2P256Mul(z3, z1, z2) + sm2P256Mul(z3, z3, &h) // z3 = z1 * z3 * h +} + +func sm2P256PointDouble(x3, y3, z3, x, y, z *sm2P256FieldElement) { + var s, m, m2, x2, y2, z2, z4, y4, az4 sm2P256FieldElement + + sm2P256Square(&x2, x) // x2 = x ^ 2 + sm2P256Square(&y2, y) // y2 = y ^ 2 + sm2P256Square(&z2, z) // z2 = z ^ 2 + + sm2P256Square(&z4, z) // z4 = z ^ 2 + sm2P256Mul(&z4, &z4, z) // z4 = z ^ 3 + sm2P256Mul(&z4, &z4, z) // z4 = z ^ 4 + + sm2P256Square(&y4, y) // y4 = y ^ 2 + sm2P256Mul(&y4, &y4, y) // y4 = y ^ 3 + sm2P256Mul(&y4, &y4, y) // y4 = y ^ 4 + sm2P256Scalar(&y4, 8) // y4 = 8 * y ^ 4 + + sm2P256Mul(&s, x, &y2) + sm2P256Scalar(&s, 4) // s = 4 * x * y ^ 2 + + sm2P256Dup(&m, &x2) + sm2P256Scalar(&m, 3) + sm2P256Mul(&az4, &sm2P256.a, &z4) + sm2P256Add(&m, &m, &az4) // m = 3 * x ^ 2 + a * z ^ 4 + + sm2P256Square(&m2, &m) // m2 = m ^ 2 + + sm2P256Add(z3, y, z) + sm2P256Square(z3, z3) + sm2P256Sub(z3, z3, &z2) + sm2P256Sub(z3, z3, &y2) // z' = (y + z) ^2 - z ^ 2 - y ^ 2 + + sm2P256Sub(x3, &m2, &s) + sm2P256Sub(x3, x3, &s) // x' = m2 - 2 * s + + sm2P256Sub(y3, &s, x3) + sm2P256Mul(y3, y3, &m) + sm2P256Sub(y3, y3, &y4) // y' = m * (s - x') - 8 * y ^ 4 +} + +// p256Zero31 is 0 mod p. +var sm2P256Zero31 = sm2P256FieldElement{0x7FFFFFF8, 0x3FFFFFFC, 0x800003FC, 0x3FFFDFFC, 0x7FFFFFFC, 0x3FFFFFFC, 0x7FFFFFFC, 0x37FFFFFC, 0x7FFFFFFC} + +// c = a + b +func sm2P256Add(c, a, b *sm2P256FieldElement) { + carry := uint32(0) + for i := 0; ; i++ { + c[i] = a[i] + b[i] + c[i] += carry + carry = c[i] >> 29 + c[i] &= bottom29Bits + i++ + if i == 9 { + break + } + c[i] = a[i] + b[i] + c[i] += carry + carry = c[i] >> 28 + c[i] &= bottom28Bits + } + sm2P256ReduceCarry(c, carry) +} + +// c = a - b +func sm2P256Sub(c, a, b *sm2P256FieldElement) { + var carry uint32 + + for i := 0; ; i++ { + c[i] = a[i] - b[i] + c[i] += sm2P256Zero31[i] + c[i] += carry + carry = c[i] >> 29 + c[i] &= bottom29Bits + i++ + if i == 9 { + break + } + c[i] = a[i] - b[i] + c[i] += sm2P256Zero31[i] + c[i] += carry + carry = c[i] >> 28 + c[i] &= bottom28Bits + } + sm2P256ReduceCarry(c, carry) +} + +// c = a * b +func sm2P256Mul(c, a, b *sm2P256FieldElement) { + var tmp sm2P256LargeFieldElement + + tmp[0] = uint64(a[0]) * uint64(b[0]) + tmp[1] = uint64(a[0])*(uint64(b[1])<<0) + + uint64(a[1])*(uint64(b[0])<<0) + tmp[2] = uint64(a[0])*(uint64(b[2])<<0) + + uint64(a[1])*(uint64(b[1])<<1) + + uint64(a[2])*(uint64(b[0])<<0) + tmp[3] = uint64(a[0])*(uint64(b[3])<<0) + + uint64(a[1])*(uint64(b[2])<<0) + + uint64(a[2])*(uint64(b[1])<<0) + + uint64(a[3])*(uint64(b[0])<<0) + tmp[4] = uint64(a[0])*(uint64(b[4])<<0) + + uint64(a[1])*(uint64(b[3])<<1) + + uint64(a[2])*(uint64(b[2])<<0) + + uint64(a[3])*(uint64(b[1])<<1) + + uint64(a[4])*(uint64(b[0])<<0) + tmp[5] = uint64(a[0])*(uint64(b[5])<<0) + + uint64(a[1])*(uint64(b[4])<<0) + + uint64(a[2])*(uint64(b[3])<<0) + + uint64(a[3])*(uint64(b[2])<<0) + + uint64(a[4])*(uint64(b[1])<<0) + + uint64(a[5])*(uint64(b[0])<<0) + tmp[6] = uint64(a[0])*(uint64(b[6])<<0) + + uint64(a[1])*(uint64(b[5])<<1) + + uint64(a[2])*(uint64(b[4])<<0) + + uint64(a[3])*(uint64(b[3])<<1) + + uint64(a[4])*(uint64(b[2])<<0) + + uint64(a[5])*(uint64(b[1])<<1) + + uint64(a[6])*(uint64(b[0])<<0) + tmp[7] = uint64(a[0])*(uint64(b[7])<<0) + + uint64(a[1])*(uint64(b[6])<<0) + + uint64(a[2])*(uint64(b[5])<<0) + + uint64(a[3])*(uint64(b[4])<<0) + + uint64(a[4])*(uint64(b[3])<<0) + + uint64(a[5])*(uint64(b[2])<<0) + + uint64(a[6])*(uint64(b[1])<<0) + + uint64(a[7])*(uint64(b[0])<<0) + // tmp[8] has the greatest value but doesn't overflow. See logic in + // p256Square. + tmp[8] = uint64(a[0])*(uint64(b[8])<<0) + + uint64(a[1])*(uint64(b[7])<<1) + + uint64(a[2])*(uint64(b[6])<<0) + + uint64(a[3])*(uint64(b[5])<<1) + + uint64(a[4])*(uint64(b[4])<<0) + + uint64(a[5])*(uint64(b[3])<<1) + + uint64(a[6])*(uint64(b[2])<<0) + + uint64(a[7])*(uint64(b[1])<<1) + + uint64(a[8])*(uint64(b[0])<<0) + tmp[9] = uint64(a[1])*(uint64(b[8])<<0) + + uint64(a[2])*(uint64(b[7])<<0) + + uint64(a[3])*(uint64(b[6])<<0) + + uint64(a[4])*(uint64(b[5])<<0) + + uint64(a[5])*(uint64(b[4])<<0) + + uint64(a[6])*(uint64(b[3])<<0) + + uint64(a[7])*(uint64(b[2])<<0) + + uint64(a[8])*(uint64(b[1])<<0) + tmp[10] = uint64(a[2])*(uint64(b[8])<<0) + + uint64(a[3])*(uint64(b[7])<<1) + + uint64(a[4])*(uint64(b[6])<<0) + + uint64(a[5])*(uint64(b[5])<<1) + + uint64(a[6])*(uint64(b[4])<<0) + + uint64(a[7])*(uint64(b[3])<<1) + + uint64(a[8])*(uint64(b[2])<<0) + tmp[11] = uint64(a[3])*(uint64(b[8])<<0) + + uint64(a[4])*(uint64(b[7])<<0) + + uint64(a[5])*(uint64(b[6])<<0) + + uint64(a[6])*(uint64(b[5])<<0) + + uint64(a[7])*(uint64(b[4])<<0) + + uint64(a[8])*(uint64(b[3])<<0) + tmp[12] = uint64(a[4])*(uint64(b[8])<<0) + + uint64(a[5])*(uint64(b[7])<<1) + + uint64(a[6])*(uint64(b[6])<<0) + + uint64(a[7])*(uint64(b[5])<<1) + + uint64(a[8])*(uint64(b[4])<<0) + tmp[13] = uint64(a[5])*(uint64(b[8])<<0) + + uint64(a[6])*(uint64(b[7])<<0) + + uint64(a[7])*(uint64(b[6])<<0) + + uint64(a[8])*(uint64(b[5])<<0) + tmp[14] = uint64(a[6])*(uint64(b[8])<<0) + + uint64(a[7])*(uint64(b[7])<<1) + + uint64(a[8])*(uint64(b[6])<<0) + tmp[15] = uint64(a[7])*(uint64(b[8])<<0) + + uint64(a[8])*(uint64(b[7])<<0) + tmp[16] = uint64(a[8]) * (uint64(b[8]) << 0) + sm2P256ReduceDegree(c, &tmp) +} + +// b = a * a +func sm2P256Square(b, a *sm2P256FieldElement) { + var tmp sm2P256LargeFieldElement + + tmp[0] = uint64(a[0]) * uint64(a[0]) + tmp[1] = uint64(a[0]) * (uint64(a[1]) << 1) + tmp[2] = uint64(a[0])*(uint64(a[2])<<1) + + uint64(a[1])*(uint64(a[1])<<1) + tmp[3] = uint64(a[0])*(uint64(a[3])<<1) + + uint64(a[1])*(uint64(a[2])<<1) + tmp[4] = uint64(a[0])*(uint64(a[4])<<1) + + uint64(a[1])*(uint64(a[3])<<2) + + uint64(a[2])*uint64(a[2]) + tmp[5] = uint64(a[0])*(uint64(a[5])<<1) + + uint64(a[1])*(uint64(a[4])<<1) + + uint64(a[2])*(uint64(a[3])<<1) + tmp[6] = uint64(a[0])*(uint64(a[6])<<1) + + uint64(a[1])*(uint64(a[5])<<2) + + uint64(a[2])*(uint64(a[4])<<1) + + uint64(a[3])*(uint64(a[3])<<1) + tmp[7] = uint64(a[0])*(uint64(a[7])<<1) + + uint64(a[1])*(uint64(a[6])<<1) + + uint64(a[2])*(uint64(a[5])<<1) + + uint64(a[3])*(uint64(a[4])<<1) + // tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60, + // which is < 2**64 as required. + tmp[8] = uint64(a[0])*(uint64(a[8])<<1) + + uint64(a[1])*(uint64(a[7])<<2) + + uint64(a[2])*(uint64(a[6])<<1) + + uint64(a[3])*(uint64(a[5])<<2) + + uint64(a[4])*uint64(a[4]) + tmp[9] = uint64(a[1])*(uint64(a[8])<<1) + + uint64(a[2])*(uint64(a[7])<<1) + + uint64(a[3])*(uint64(a[6])<<1) + + uint64(a[4])*(uint64(a[5])<<1) + tmp[10] = uint64(a[2])*(uint64(a[8])<<1) + + uint64(a[3])*(uint64(a[7])<<2) + + uint64(a[4])*(uint64(a[6])<<1) + + uint64(a[5])*(uint64(a[5])<<1) + tmp[11] = uint64(a[3])*(uint64(a[8])<<1) + + uint64(a[4])*(uint64(a[7])<<1) + + uint64(a[5])*(uint64(a[6])<<1) + tmp[12] = uint64(a[4])*(uint64(a[8])<<1) + + uint64(a[5])*(uint64(a[7])<<2) + + uint64(a[6])*uint64(a[6]) + tmp[13] = uint64(a[5])*(uint64(a[8])<<1) + + uint64(a[6])*(uint64(a[7])<<1) + tmp[14] = uint64(a[6])*(uint64(a[8])<<1) + + uint64(a[7])*(uint64(a[7])<<1) + tmp[15] = uint64(a[7]) * (uint64(a[8]) << 1) + tmp[16] = uint64(a[8]) * uint64(a[8]) + sm2P256ReduceDegree(b, &tmp) +} + +// nonZeroToAllOnes returns: +// +// 0xffffffff for 0 < x <= 2**31 +// 0 for x == 0 or x > 2**31. +func nonZeroToAllOnes(x uint32) uint32 { + return ((x - 1) >> 31) - 1 +} + +var sm2P256Carry = [8 * 9]uint32{ + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x2, 0x0, 0x1FFFFF00, 0x7FF, 0x0, 0x0, 0x0, 0x2000000, 0x0, + 0x4, 0x0, 0x1FFFFE00, 0xFFF, 0x0, 0x0, 0x0, 0x4000000, 0x0, + 0x6, 0x0, 0x1FFFFD00, 0x17FF, 0x0, 0x0, 0x0, 0x6000000, 0x0, + 0x8, 0x0, 0x1FFFFC00, 0x1FFF, 0x0, 0x0, 0x0, 0x8000000, 0x0, + 0xA, 0x0, 0x1FFFFB00, 0x27FF, 0x0, 0x0, 0x0, 0xA000000, 0x0, + 0xC, 0x0, 0x1FFFFA00, 0x2FFF, 0x0, 0x0, 0x0, 0xC000000, 0x0, + 0xE, 0x0, 0x1FFFF900, 0x37FF, 0x0, 0x0, 0x0, 0xE000000, 0x0, +} + +// carry < 2 ^ 3 +func sm2P256ReduceCarry(a *sm2P256FieldElement, carry uint32) { + a[0] += sm2P256Carry[carry*9+0] + a[2] += sm2P256Carry[carry*9+2] + a[3] += sm2P256Carry[carry*9+3] + a[7] += sm2P256Carry[carry*9+7] +} + +func sm2P256ReduceDegree(a *sm2P256FieldElement, b *sm2P256LargeFieldElement) { + var tmp [18]uint32 + var carry, x, xMask uint32 + + // tmp + // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 ... + // 29 | 28 | 29 | 28 | 29 | 28 | 29 | 28 | 29 | 28 | 29 ... + tmp[0] = uint32(b[0]) & bottom29Bits + tmp[1] = uint32(b[0]) >> 29 + tmp[1] |= (uint32(b[0]>>32) << 3) & bottom28Bits + tmp[1] += uint32(b[1]) & bottom28Bits + carry = tmp[1] >> 28 + tmp[1] &= bottom28Bits + for i := 2; i < 17; i++ { + tmp[i] = (uint32(b[i-2] >> 32)) >> 25 + tmp[i] += (uint32(b[i-1])) >> 28 + tmp[i] += (uint32(b[i-1]>>32) << 4) & bottom29Bits + tmp[i] += uint32(b[i]) & bottom29Bits + tmp[i] += carry + carry = tmp[i] >> 29 + tmp[i] &= bottom29Bits + + i++ + if i == 17 { + break + } + tmp[i] = uint32(b[i-2]>>32) >> 25 + tmp[i] += uint32(b[i-1]) >> 29 + tmp[i] += ((uint32(b[i-1] >> 32)) << 3) & bottom28Bits + tmp[i] += uint32(b[i]) & bottom28Bits + tmp[i] += carry + carry = tmp[i] >> 28 + tmp[i] &= bottom28Bits + } + tmp[17] = uint32(b[15]>>32) >> 25 + tmp[17] += uint32(b[16]) >> 29 + tmp[17] += uint32(b[16]>>32) << 3 + tmp[17] += carry + + for i := 0; ; i += 2 { + + tmp[i+1] += tmp[i] >> 29 + x = tmp[i] & bottom29Bits + tmp[i] = 0 + if x > 0 { + set4 := uint32(0) + set7 := uint32(0) + xMask = nonZeroToAllOnes(x) + tmp[i+2] += (x << 7) & bottom29Bits + tmp[i+3] += x >> 22 + if tmp[i+3] < 0x10000000 { + set4 = 1 + tmp[i+3] += 0x10000000 & xMask + tmp[i+3] -= (x << 10) & bottom28Bits + } else { + tmp[i+3] -= (x << 10) & bottom28Bits + } + if tmp[i+4] < 0x20000000 { + tmp[i+4] += 0x20000000 & xMask + tmp[i+4] -= set4 // 借位 + tmp[i+4] -= x >> 18 + if tmp[i+5] < 0x10000000 { + tmp[i+5] += 0x10000000 & xMask + tmp[i+5] -= 1 // 借位 + if tmp[i+6] < 0x20000000 { + set7 = 1 + tmp[i+6] += 0x20000000 & xMask + tmp[i+6] -= 1 // 借位 + } else { + tmp[i+6] -= 1 // 借位 + } + } else { + tmp[i+5] -= 1 + } + } else { + tmp[i+4] -= set4 // 借位 + tmp[i+4] -= x >> 18 + } + if tmp[i+7] < 0x10000000 { + tmp[i+7] += 0x10000000 & xMask + tmp[i+7] -= set7 + tmp[i+7] -= (x << 24) & bottom28Bits + tmp[i+8] += (x << 28) & bottom29Bits + if tmp[i+8] < 0x20000000 { + tmp[i+8] += 0x20000000 & xMask + tmp[i+8] -= 1 + tmp[i+8] -= x >> 4 + tmp[i+9] += ((x >> 1) - 1) & xMask + } else { + tmp[i+8] -= 1 + tmp[i+8] -= x >> 4 + tmp[i+9] += (x >> 1) & xMask + } + } else { + tmp[i+7] -= set7 // 借位 + tmp[i+7] -= (x << 24) & bottom28Bits + tmp[i+8] += (x << 28) & bottom29Bits + if tmp[i+8] < 0x20000000 { + tmp[i+8] += 0x20000000 & xMask + tmp[i+8] -= x >> 4 + tmp[i+9] += ((x >> 1) - 1) & xMask + } else { + tmp[i+8] -= x >> 4 + tmp[i+9] += (x >> 1) & xMask + } + } + + } + + if i+1 == 9 { + break + } + + tmp[i+2] += tmp[i+1] >> 28 + x = tmp[i+1] & bottom28Bits + tmp[i+1] = 0 + if x > 0 { + set5 := uint32(0) + set8 := uint32(0) + set9 := uint32(0) + xMask = nonZeroToAllOnes(x) + tmp[i+3] += (x << 7) & bottom28Bits + tmp[i+4] += x >> 21 + if tmp[i+4] < 0x20000000 { + set5 = 1 + tmp[i+4] += 0x20000000 & xMask + tmp[i+4] -= (x << 11) & bottom29Bits + } else { + tmp[i+4] -= (x << 11) & bottom29Bits + } + if tmp[i+5] < 0x10000000 { + tmp[i+5] += 0x10000000 & xMask + tmp[i+5] -= set5 // 借位 + tmp[i+5] -= x >> 18 + if tmp[i+6] < 0x20000000 { + tmp[i+6] += 0x20000000 & xMask + tmp[i+6] -= 1 // 借位 + if tmp[i+7] < 0x10000000 { + set8 = 1 + tmp[i+7] += 0x10000000 & xMask + tmp[i+7] -= 1 // 借位 + } else { + tmp[i+7] -= 1 // 借位 + } + } else { + tmp[i+6] -= 1 // 借位 + } + } else { + tmp[i+5] -= set5 // 借位 + tmp[i+5] -= x >> 18 + } + if tmp[i+8] < 0x20000000 { + set9 = 1 + tmp[i+8] += 0x20000000 & xMask + tmp[i+8] -= set8 + tmp[i+8] -= (x << 25) & bottom29Bits + } else { + tmp[i+8] -= set8 + tmp[i+8] -= (x << 25) & bottom29Bits + } + if tmp[i+9] < 0x10000000 { + tmp[i+9] += 0x10000000 & xMask + tmp[i+9] -= set9 // 借位 + tmp[i+9] -= x >> 4 + tmp[i+10] += (x - 1) & xMask + } else { + tmp[i+9] -= set9 // 借位 + tmp[i+9] -= x >> 4 + tmp[i+10] += x & xMask + } + } + } + + carry = uint32(0) + for i := 0; i < 8; i++ { + a[i] = tmp[i+9] + a[i] += carry + a[i] += (tmp[i+10] << 28) & bottom29Bits + carry = a[i] >> 29 + a[i] &= bottom29Bits + + i++ + a[i] = tmp[i+9] >> 1 + a[i] += carry + carry = a[i] >> 28 + a[i] &= bottom28Bits + } + a[8] = tmp[17] + a[8] += carry + carry = a[8] >> 29 + a[8] &= bottom29Bits + sm2P256ReduceCarry(a, carry) +} + +// b = a +func sm2P256Dup(b, a *sm2P256FieldElement) { + *b = *a +} + +// X = a * R mod P +func sm2P256FromBig(X *sm2P256FieldElement, a *big.Int) { + x := new(big.Int).Lsh(a, 257) + x.Mod(x, sm2P256.P) + for i := 0; i < 9; i++ { + if bits := x.Bits(); len(bits) > 0 { + X[i] = uint32(bits[0]) & bottom29Bits + } else { + X[i] = 0 + } + x.Rsh(x, 29) + i++ + if i == 9 { + break + } + if bits := x.Bits(); len(bits) > 0 { + X[i] = uint32(bits[0]) & bottom28Bits + } else { + X[i] = 0 + } + x.Rsh(x, 28) + } +} + +// X = r * R mod P +// r = X * R' mod P +func sm2P256ToBig(X *sm2P256FieldElement) *big.Int { + r, tm := new(big.Int), new(big.Int) + r.SetInt64(int64(X[8])) + for i := 7; i >= 0; i-- { + if (i & 1) == 0 { + r.Lsh(r, 29) + } else { + r.Lsh(r, 28) + } + tm.SetInt64(int64(X[i])) + r.Add(r, tm) + } + r.Mul(r, sm2P256.RInverse) + r.Mod(r, sm2P256.P) + return r +} +func WNafReversed(wnaf []int8) []int8 { + wnafRev := make([]int8, len(wnaf), len(wnaf)) + for i, v := range wnaf { + wnafRev[len(wnaf)-(1+i)] = v + } + return wnafRev +} +func sm2GenrateWNaf(b []byte) []int8 { + n := new(big.Int).SetBytes(b) + var k *big.Int + if n.Cmp(sm2P256.N) >= 0 { + n.Mod(n, sm2P256.N) + k = n + } else { + k = n + } + wnaf := make([]int8, k.BitLen()+1, k.BitLen()+1) + if k.Sign() == 0 { + return wnaf + } + var width, pow2, sign int + width, pow2, sign = 4, 16, 8 + var mask int64 = 15 + var carry bool + var length, pos int + for pos <= k.BitLen() { + if k.Bit(pos) == boolToUint(carry) { + pos++ + continue + } + k.Rsh(k, uint(pos)) + var digit int + digit = int(k.Int64() & mask) + if carry { + digit++ + } + carry = (digit & sign) != 0 + if carry { + digit -= pow2 + } + length += pos + wnaf[length] = int8(digit) + pos = int(width) + } + if len(wnaf) > length+1 { + t := make([]int8, length+1, length+1) + copy(t, wnaf[0:length+1]) + wnaf = t + } + return wnaf +} +func boolToUint(b bool) uint { + if b { + return 1 + } + return 0 +} +func abs(a int8) uint32 { + if a < 0 { + return uint32(-a) + } + return uint32(a) +} + +func sm2P256ScalarMult(xOut, yOut, zOut, x, y *sm2P256FieldElement, scalar []int8) { + var precomp [16][3]sm2P256FieldElement + var px, py, pz, tx, ty, tz sm2P256FieldElement + var nIsInfinityMask, index, pIsNoninfiniteMask, mask uint32 + + // We precompute 0,1,2,... times {x,y}. + precomp[1][0] = *x + precomp[1][1] = *y + precomp[1][2] = sm2P256Factor[1] + + for i := 2; i < 8; i += 2 { + sm2P256PointDouble(&precomp[i][0], &precomp[i][1], &precomp[i][2], &precomp[i/2][0], &precomp[i/2][1], &precomp[i/2][2]) + sm2P256PointAddMixed(&precomp[i+1][0], &precomp[i+1][1], &precomp[i+1][2], &precomp[i][0], &precomp[i][1], &precomp[i][2], x, y) + } + + for i := range xOut { + xOut[i] = 0 + } + for i := range yOut { + yOut[i] = 0 + } + for i := range zOut { + zOut[i] = 0 + } + nIsInfinityMask = ^uint32(0) + var zeroes int16 + for i := 0; i < len(scalar); i++ { + if scalar[i] == 0 { + zeroes++ + continue + } + if zeroes > 0 { + for ; zeroes > 0; zeroes-- { + sm2P256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) + } + } + index = abs(scalar[i]) + sm2P256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) + sm2P256SelectJacobianPoint(&px, &py, &pz, &precomp, index) + if scalar[i] > 0 { + sm2P256PointAdd(xOut, yOut, zOut, &px, &py, &pz, &tx, &ty, &tz) + } else { + sm2P256PointSub(xOut, yOut, zOut, &px, &py, &pz, &tx, &ty, &tz) + } + sm2P256CopyConditional(xOut, &px, nIsInfinityMask) + sm2P256CopyConditional(yOut, &py, nIsInfinityMask) + sm2P256CopyConditional(zOut, &pz, nIsInfinityMask) + pIsNoninfiniteMask = nonZeroToAllOnes(index) + mask = pIsNoninfiniteMask & ^nIsInfinityMask + sm2P256CopyConditional(xOut, &tx, mask) + sm2P256CopyConditional(yOut, &ty, mask) + sm2P256CopyConditional(zOut, &tz, mask) + nIsInfinityMask &^= pIsNoninfiniteMask + } + if zeroes > 0 { + for ; zeroes > 0; zeroes-- { + sm2P256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) + } + } +} diff --git a/app/utils/encrypt/sm4/internal/sm2/readme.md b/app/utils/encrypt/sm4/internal/sm2/readme.md new file mode 100644 index 0000000..ff589c4 --- /dev/null +++ b/app/utils/encrypt/sm4/internal/sm2/readme.md @@ -0,0 +1,2 @@ +* 来源于 github.com/tjfoc/gmsm +* 修改适配 邮储对接 \ No newline at end of file diff --git a/app/utils/encrypt/sm4/internal/sm2/sm2.go b/app/utils/encrypt/sm4/internal/sm2/sm2.go new file mode 100644 index 0000000..32d907e --- /dev/null +++ b/app/utils/encrypt/sm4/internal/sm2/sm2.go @@ -0,0 +1,219 @@ +package sm2 + +// reference to ecdsa +import ( + "crypto" + "crypto/elliptic" + "crypto/rand" + "encoding/asn1" + "errors" + "github.com/tjfoc/gmsm/sm3" + "io" + "math/big" +) + +var ( + default_uid = []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38} +) + +type PublicKey struct { + elliptic.Curve + X, Y *big.Int +} + +type PrivateKey struct { + PublicKey + D *big.Int +} + +type sm2Signature struct { + R, S *big.Int +} + +func (priv *PrivateKey) Public() crypto.PublicKey { + return &priv.PublicKey +} + +var errZeroParam = errors.New("zero parameter") +var one = new(big.Int).SetInt64(1) +var two = new(big.Int).SetInt64(2) + +func (priv *PrivateKey) Sign(random io.Reader, msg []byte, signer crypto.SignerOpts) ([]byte, error) { + r, s, err := Sm2Sign(priv, msg, nil, random) + if err != nil { + return nil, err + } + return asn1.Marshal(sm2Signature{r, s}) +} + +func Sm2Sign(priv *PrivateKey, msg, uid []byte, random io.Reader) (r, s *big.Int, err error) { + digest, err := priv.PublicKey.Sm3Digest(msg, uid) + if err != nil { + return nil, nil, err + } + e := new(big.Int).SetBytes(digest) + c := priv.PublicKey.Curve + N := c.Params().N + if N.Sign() == 0 { + return nil, nil, errZeroParam + } + var k *big.Int + for { // 调整算法细节以实现SM2 + for { + k, err = randFieldElement(c, random) + if err != nil { + r = nil + return + } + r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) + r.Add(r, e) + r.Mod(r, N) + if r.Sign() != 0 { + if t := new(big.Int).Add(r, k); t.Cmp(N) != 0 { + break + } + } + + } + rD := new(big.Int).Mul(priv.D, r) + s = new(big.Int).Sub(k, rD) + d1 := new(big.Int).Add(priv.D, one) + d1Inv := new(big.Int).ModInverse(d1, N) + s.Mul(s, d1Inv) + s.Mod(s, N) + if s.Sign() != 0 { + break + } + } + return +} + +func (pub *PublicKey) Sm3Digest(msg, uid []byte) ([]byte, error) { + if len(uid) == 0 { + uid = default_uid + } + + za, err := getZ(pub, uid) + if err != nil { + return nil, err + } + + e, err := msgHash(za, msg) + if err != nil { + return nil, err + } + + return e.Bytes(), nil +} + +func Sm2Verify(pub *PublicKey, msg, uid []byte, r, s *big.Int) bool { + c := pub.Curve + N := c.Params().N + one := new(big.Int).SetInt64(1) + if r.Cmp(one) < 0 || s.Cmp(one) < 0 { + return false + } + if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 { + return false + } + if len(uid) == 0 { + uid = default_uid + } + za, err := getZ(pub, uid) + if err != nil { + return false + } + e, err := msgHash(za, msg) + if err != nil { + return false + } + t := new(big.Int).Add(r, s) + t.Mod(t, N) + if t.Sign() == 0 { + return false + } + var x *big.Int + x1, y1 := c.ScalarBaseMult(s.Bytes()) + x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes()) + x, _ = c.Add(x1, y1, x2, y2) + + x.Add(x, e) + x.Mod(x, N) + return x.Cmp(r) == 0 +} + +func msgHash(za, msg []byte) (*big.Int, error) { + e := sm3.New() + e.Write(za) + e.Write(msg) + return new(big.Int).SetBytes(e.Sum(nil)[:32]), nil +} + +func bigIntToByte(n *big.Int) []byte { + byteArray := n.Bytes() + // If the most significant byte's most significant bit is set, + // prepend a 0 byte to the slice to avoid being interpreted as a negative number. + if (byteArray[0] & 0x80) != 0 { + byteArray = append([]byte{0}, byteArray...) + } + return byteArray +} + +func getZ(pub *PublicKey, uid []byte) ([]byte, error) { + z := sm3.New() + uidLen := len(uid) * 8 + entla := []byte{byte(uidLen >> 8), byte(uidLen & 255)} + z.Write(entla) + z.Write(uid) + + // a 先写死,原来的没有暴露 + z.Write(bigIntToByte(sm2P256ToBig(&sm2P256.a))) + z.Write(bigIntToByte(sm2P256.B)) + z.Write(bigIntToByte(sm2P256.Gx)) + z.Write(bigIntToByte(sm2P256.Gy)) + + z.Write(bigIntToByte(pub.X)) + z.Write(bigIntToByte(pub.Y)) + return z.Sum(nil), nil +} + +func randFieldElement(c elliptic.Curve, random io.Reader) (k *big.Int, err error) { + if random == nil { + random = rand.Reader //If there is no external trusted random source,please use rand.Reader to instead of it. + } + params := c.Params() + b := make([]byte, params.BitSize/8+8) + _, err = io.ReadFull(random, b) + if err != nil { + return + } + k = new(big.Int).SetBytes(b) + n := new(big.Int).Sub(params.N, one) + k.Mod(k, n) + k.Add(k, one) + return +} + +func GenerateKey(random io.Reader) (*PrivateKey, error) { + c := P256Sm2() + if random == nil { + random = rand.Reader //If there is no external trusted random source,please use rand.Reader to instead of it. + } + params := c.Params() + b := make([]byte, params.BitSize/8+8) + _, err := io.ReadFull(random, b) + if err != nil { + return nil, err + } + + k := new(big.Int).SetBytes(b) + n := new(big.Int).Sub(params.N, two) + k.Mod(k, n) + k.Add(k, one) + priv := new(PrivateKey) + priv.PublicKey.Curve = c + priv.D = k + priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes()) + + return priv, nil +} diff --git a/app/utils/encrypt/sm4/internal/sm2/utils.go b/app/utils/encrypt/sm4/internal/sm2/utils.go new file mode 100644 index 0000000..6b09718 --- /dev/null +++ b/app/utils/encrypt/sm4/internal/sm2/utils.go @@ -0,0 +1,45 @@ +package sm2 + +import ( + "encoding/hex" + "errors" + "math/big" +) + +func ReadPrivateKeyFromHex(Dhex string) (*PrivateKey, error) { + c := P256Sm2() + d, err := hex.DecodeString(Dhex) + if err != nil { + return nil, err + } + k := new(big.Int).SetBytes(d) + params := c.Params() + one := new(big.Int).SetInt64(1) + n := new(big.Int).Sub(params.N, one) + if k.Cmp(n) >= 0 { + return nil, errors.New("privateKey's D is overflow.") + } + priv := new(PrivateKey) + priv.PublicKey.Curve = c + priv.D = k + priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes()) + return priv, nil +} + +func ReadPublicKeyFromHex(Qhex string) (*PublicKey, error) { + q, err := hex.DecodeString(Qhex) + if err != nil { + return nil, err + } + if len(q) == 65 && q[0] == byte(0x04) { + q = q[1:] + } + if len(q) != 64 { + return nil, errors.New("publicKey is not uncompressed.") + } + pub := new(PublicKey) + pub.Curve = P256Sm2() + pub.X = new(big.Int).SetBytes(q[:32]) + pub.Y = new(big.Int).SetBytes(q[32:]) + return pub, nil +} diff --git a/app/utils/encrypt/sm4/internal/util/sm2x.go b/app/utils/encrypt/sm4/internal/util/sm2x.go new file mode 100644 index 0000000..9253e33 --- /dev/null +++ b/app/utils/encrypt/sm4/internal/util/sm2x.go @@ -0,0 +1,163 @@ +package util + +import ( + "PaymentCenter/app/utils/encrypt/sm4/internal/sm2" + "bytes" + "crypto/elliptic" + "crypto/rand" + "errors" + zzsm2 "github.com/ZZMarquis/gm/sm2" + "github.com/tjfoc/gmsm/sm3" + "github.com/tjfoc/gmsm/x509" + "math/big" +) + +func Sm2Decrypt(privateKey *sm2.PrivateKey, encryptData []byte) ([]byte, error) { + C1Byte := make([]byte, 65) + copy(C1Byte, encryptData[:65]) + x, y := elliptic.Unmarshal(privateKey.Curve, C1Byte) + dBC1X, dBC1Y := privateKey.Curve.ScalarMult(x, y, bigIntToByte(privateKey.D)) + dBC1Bytes := elliptic.Marshal(privateKey.Curve, dBC1X, dBC1Y) + + kLen := len(encryptData) - 65 - 32 + t, err := kdf(dBC1Bytes, kLen) + if err != nil { + return nil, err + } + + M := make([]byte, kLen) + for i := 0; i < kLen; i++ { + M[i] = encryptData[65+i] ^ t[i] + } + + C3 := make([]byte, 32) + copy(C3, encryptData[len(encryptData)-32:]) + u := calculateHash(dBC1X, M, dBC1Y) + + if bytes.Compare(u, C3) == 0 { + return M, nil + } else { + return nil, errors.New("解密失败") + } +} + +func Sm2Encrypt(publicKey *sm2.PublicKey, m []byte) ([]byte, error) { + kLen := len(m) + var C1, t []byte + var err error + var kx, ky *big.Int + for { + k, _ := rand.Int(rand.Reader, publicKey.Params().N) + C1x, C1y := zzsm2.GetSm2P256V1().ScalarBaseMult(bigIntToByte(k)) + // C1x, C1y := sm2.P256Sm2().ScalarBaseMult(bigIntToByte(k)) + C1 = elliptic.Marshal(publicKey.Curve, C1x, C1y) + + kx, ky = publicKey.ScalarMult(publicKey.X, publicKey.Y, bigIntToByte(k)) + kpbBytes := elliptic.Marshal(publicKey, kx, ky) + t, err = kdf(kpbBytes, kLen) + if err != nil { + return nil, err + } + if !isAllZero(t) { + break + } + } + + C2 := make([]byte, kLen) + for i := 0; i < kLen; i++ { + C2[i] = m[i] ^ t[i] + } + + C3 := calculateHash(kx, m, ky) + + r := make([]byte, 0, len(C1)+len(C2)+len(C3)) + r = append(r, C1...) + r = append(r, C2...) + r = append(r, C3...) + return r, nil +} + +func isAllZero(m []byte) bool { + for i := 0; i < len(m); i++ { + if m[i] != 0 { + return false + } + } + return true +} + +func calculateHash(x *big.Int, M []byte, y *big.Int) []byte { + digest := sm3.New() + digest.Write(bigIntToByte(x)) + digest.Write(M) + digest.Write(bigIntToByte(y)) + result := digest.Sum(nil)[:32] + return result +} + +func bigIntToByte(n *big.Int) []byte { + byteArray := n.Bytes() + // If the most significant byte's most significant bit is set, + // prepend a 0 byte to the slice to avoid being interpreted as a negative number. + if (byteArray[0] & 0x80) != 0 { + byteArray = append([]byte{0}, byteArray...) + } + return byteArray +} + +func kdf(Z []byte, klen int) ([]byte, error) { + ct := 1 + end := (klen + 31) / 32 + result := make([]byte, 0) + for i := 1; i <= end; i++ { + b, err := sm3hash(Z, toByteArray(ct)) + if err != nil { + return nil, err + } + result = append(result, b...) + ct++ + } + last, err := sm3hash(Z, toByteArray(ct)) + if err != nil { + return nil, err + } + if klen%32 == 0 { + result = append(result, last...) + } else { + result = append(result, last[:klen%32]...) + } + return result, nil +} + +func sm3hash(sources ...[]byte) ([]byte, error) { + b, err := joinBytes(sources...) + if err != nil { + return nil, err + } + md := make([]byte, 32) + h := x509.SM3.New() + h.Write(b) + h.Sum(md[:0]) + return md, nil +} + +func joinBytes(params ...[]byte) ([]byte, error) { + var buffer bytes.Buffer + for i := 0; i < len(params); i++ { + _, err := buffer.Write(params[i]) + if err != nil { + return nil, err + } + } + return buffer.Bytes(), nil +} + +func toByteArray(i int) []byte { + byteArray := []byte{ + byte(i >> 24), + byte((i & 16777215) >> 16), + byte((i & 65535) >> 8), + byte(i & 255), + } + return byteArray +} diff --git a/app/utils/encrypt/sm4/internal/util/smutil.go b/app/utils/encrypt/sm4/internal/util/smutil.go new file mode 100644 index 0000000..f0773ff --- /dev/null +++ b/app/utils/encrypt/sm4/internal/util/smutil.go @@ -0,0 +1,62 @@ +package util + +import ( + "crypto/md5" + "crypto/rand" + "encoding/hex" + "math/big" + "strings" + "time" +) + +func GenerateSM4Key() []byte { + str := "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890" + buffer := make([]byte, 16) + for i := 0; i < 16; i++ { + nextInt, _ := rand.Int(rand.Reader, big.NewInt(int64(len(str)))) + buffer[i] = str[nextInt.Int64()] + } + return buffer +} + +func GenAccessToken(token string) string { + if token != "" { + return token + } + now := time.Now() + return strings.ToUpper(Md5Hash(now.Format("2006A01B02CD15E04F05"), "")) +} + +func Md5Hash(password, salt string) string { + m := md5.New() + m.Write([]byte(salt + password)) + return hex.EncodeToString(m.Sum(nil)) +} + +// GetSM4IV 获取SM4的IV +func GetSM4IV() []byte { + return []byte("UISwD9fW6cFh9SNS") +} + +func Padding(input []byte, mode int) []byte { + if input == nil { + return nil + } else { + var ret []byte + if mode == 1 { + p := 16 - len(input)%16 + ret = make([]byte, len(input)+p) + copy(ret, input) + + for i := 0; i < p; i++ { + ret[len(input)+i] = byte(p) + } + } else { + p := input[len(input)-1] + ret = make([]byte, len(input)-int(p)) + copy(ret, input[:len(input)-int(p)]) + } + + return ret + } +} diff --git a/app/utils/encrypt/sm4/sm.go b/app/utils/encrypt/sm4/sm.go new file mode 100644 index 0000000..ad89e0d --- /dev/null +++ b/app/utils/encrypt/sm4/sm.go @@ -0,0 +1,203 @@ +package sm4 + +import ( + "PaymentCenter/app/utils/encrypt/sm4/internal/sm2" + "PaymentCenter/app/utils/encrypt/sm4/internal/util" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "github.com/ZZMarquis/gm/sm4" + "math/big" + "strings" +) + +func checkInData(reqData map[string]string, key string) (string, error) { + data, ok := reqData[key] + if !ok { + return "", errors.New("请求数据中不存在" + key) + } + return data, nil +} + +func Sm4Decrypt(merchantId, privateKey, sopPublicKey, respJson string, isRequest bool) (string, error) { + var reqData map[string]string + err := json.Unmarshal([]byte(respJson), &reqData) + if err != nil { + return "", err + } + + keys := [4]string{} + if isRequest { + keys = [4]string{"request", "signature", "encryptKey", "accessToken"} + } else { + keys = [4]string{"response", "signature", "encryptKey", "accessToken"} + } + var inEncryptKey, inAccessToken, inData, inSignature string + + for i := 0; i < 4; i++ { + data, err := checkInData(reqData, keys[i]) + if err != nil { + return "", err + } + switch keys[i] { + case "request", "response": + inData = data + case "signature": + inSignature = data + case "encryptKey": + inEncryptKey = data + case "accessToken": + inAccessToken = data + } + } + + checked := verify(fmt.Sprintf("%s%s%s", inData, inEncryptKey, inAccessToken), inSignature, sopPublicKey, merchantId) + if !checked { + return "", errors.New("签名验证失败") + } + + priKey, err := sm2.ReadPrivateKeyFromHex(privateKey) + if err != nil { + return "", errors.New("读取私钥失败") + } + hexEncryptKey, err := hex.DecodeString(inEncryptKey) + if err != nil { + return "", errors.New("解密sm4key失败") + } + sm4Key, err := util.Sm2Decrypt(priKey, hexEncryptKey) + + request, _ := base64.StdEncoding.DecodeString(inData) + + encryptedSm4Key, err := sm4.CBCDecrypt(sm4Key, util.GetSM4IV(), request) + + return string(util.Padding(encryptedSm4Key, 0)), nil +} + +func Sm4Encrypt(merchantId, privateKey, sopPublicKey, inputJson, token string, isRequest bool) (string, error) { + sm4Key := util.GenerateSM4Key() + iv := util.GetSM4IV() + tmp, err := sm4.CBCEncrypt(sm4Key, iv, util.Padding([]byte(inputJson), 1)) + if err != nil { + return "", err + } + responseMsg := base64.StdEncoding.EncodeToString(tmp) + responseMsg = addNewline(responseMsg) + + pubKey, err := sm2.ReadPublicKeyFromHex(sopPublicKey) + if err != nil { + return "", errors.New("读取私钥失败") + } + encryptKeyBytes, err := util.Sm2Encrypt(pubKey, sm4Key) + encryptKey := strings.ToUpper(hex.EncodeToString(encryptKeyBytes)) + + accessToken := util.GenAccessToken(token) + signContent := fmt.Sprintf("%s%s%s", responseMsg, encryptKey, accessToken) + signature, err := sign(merchantId, privateKey, signContent) + + var reqData map[string]string + + if isRequest { + reqData = map[string]string{ + "request": responseMsg, + "signature": signature, + "encryptKey": encryptKey, + "accessToken": accessToken, + } + } else { + reqData = map[string]string{ + "response": responseMsg, + "signature": signature, + "encryptKey": encryptKey, + "accessToken": accessToken, + } + } + + jsonStr, err := json.Marshal(reqData) + if err != nil { + return "", err + } + return string(jsonStr), err +} + +// GenerateKey 生成密钥对 +func GenerateKey() (string, string) { + pri, _ := sm2.GenerateKey(rand.Reader) + hexPri := pri.D.Text(16) + // 获取公钥 + publicKeyHex := publicKeyToString(&pri.PublicKey) + return strings.ToUpper(hexPri), publicKeyHex +} + +// publicKeyToString 公钥sm2.PublicKey转字符串(与java中org.bouncycastle.crypto生成的公私钥完全互通使用) +func publicKeyToString(publicKey *sm2.PublicKey) string { + xBytes := publicKey.X.Bytes() + yBytes := publicKey.Y.Bytes() + + // 确保坐标字节切片长度相同 + byteLen := len(xBytes) + if len(yBytes) > byteLen { + byteLen = len(yBytes) + } + + // 为坐标补齐前导零 + xBytes = append(make([]byte, byteLen-len(xBytes)), xBytes...) + yBytes = append(make([]byte, byteLen-len(yBytes)), yBytes...) + + // 添加 "04" 前缀 + publicKeyBytes := append([]byte{0x04}, append(xBytes, yBytes...)...) + + return strings.ToUpper(hex.EncodeToString(publicKeyBytes)) +} + +func addNewline(str string) string { + lineLength := 76 + var result strings.Builder + for i := 0; i < len(str); i++ { + if i > 0 && i%lineLength == 0 { + result.WriteString("\r\n") + } + result.WriteByte(str[i]) + } + return result.String() +} + +func sign(merchantId string, privateKeyHex string, signContent string) (string, error) { + privateKey, err := sm2.ReadPrivateKeyFromHex(privateKeyHex) + if err != nil { + return "", err + } + + r, s, err := sm2.Sm2Sign(privateKey, []byte(signContent), []byte(merchantId), rand.Reader) + if err != nil { + return "", err + } + return rSToSign(r, s), nil +} + +func verify(content string, signature string, publicKeyStr string, merchantId string) bool { + pubKey, err := sm2.ReadPublicKeyFromHex(publicKeyStr) + if err != nil { + panic(fmt.Sprintf("pubKeyBytes sm2 ReadPublicKeyFromHex err: %v", err)) + } + r, s := signToRS(signature) + return sm2.Sm2Verify(pubKey, []byte(content), []byte(merchantId), r, s) +} + +func signToRS(signStr string) (*big.Int, *big.Int) { + signSub := strings.Split(signStr, "#") + if len(signSub) != 2 { + panic(fmt.Sprintf("err rs: %x", signSub)) + } + r, _ := new(big.Int).SetString(signSub[0], 16) + s, _ := new(big.Int).SetString(signSub[1], 16) + return r, s +} + +func rSToSign(r *big.Int, s *big.Int) string { + rStr := r.Text(16) + sStr := s.Text(16) + return fmt.Sprintf("%s#%s", rStr, sStr) +} diff --git a/app/utils/encrypt/sm4/sm4_test.go b/app/utils/encrypt/sm4/sm4_test.go new file mode 100644 index 0000000..555456c --- /dev/null +++ b/app/utils/encrypt/sm4/sm4_test.go @@ -0,0 +1,44 @@ +package sm4 + +import ( + "fmt" + "testing" +) + +const ( + SELF_PRI = "EA7CB6F907A96264D6763F8C46AB96B476538D2ABC880A459E10BE5A1C30013D" + + SELF_PUB = "04363DF574D4FE34EE58FB8A3F7CB08E6CA5EBB3B7335CBAE10A2900551F6450AB3AD25DBC0A76EFA9E6D44D2C51E3027483F7BFD09996457888BAFD1AF673817F" + + PARTY_PRI = "EEB0A34DE1F05154E4B96E50BFC1F8B9750EEAE799F5708C7AFBABB9AFCFA1BF" + + PARTY_PUB = "0420425DF33945C9D5596A33ED60ABEEFD0165C27BA7D6C95D37344E9223149FEAF4C10CEACD7EC88E8DD1E0BDEA71FD09BE2077A1BDC61BC45587B7CC3613F85A" +) + +func TestGenerateKey(t *testing.T) { + hexPri, publicKeyHex := GenerateKey() + fmt.Println(hexPri, publicKeyHex) +} + +func TestSM4Encrypt(t *testing.T) { + t.Log(encrypt()) +} + +func TestSM4Decrypt(t *testing.T) { + uid, en := encrypt() + decrypt, err := Sm4Decrypt(uid, SELF_PRI, PARTY_PUB, en, true) + if err != nil { + panic(err) + } + t.Log(decrypt) +} + +func encrypt() (string, string) { + uid := "1234567890" + data := "{\"name\":\"张三\",\"sex\":1,\"is_human\":true}" + en, err := Sm4Encrypt(uid, PARTY_PRI, SELF_PUB, data, "", true) + if err != nil { + panic(err) + } + return uid, en +} diff --git a/app/utils/util.go b/app/utils/util.go index 0810033..9427626 100644 --- a/app/utils/util.go +++ b/app/utils/util.go @@ -11,6 +11,7 @@ import ( "encoding/hex" "fmt" "github.com/aliyun/aliyun-oss-go-sdk/oss" + "github.com/bytedance/sonic" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v4" "github.com/pkg/errors" @@ -411,6 +412,35 @@ func ParseToken(tokenString string) (*jwt.Token, *Claims, error) { return token, Claims, err } +func PopLast[T any](slice *[]T) (T, bool) { + if len(*slice) == 0 { + var zero T + return zero, false + } + index := len(*slice) - 1 + lastElement := (*slice)[index] + *slice = (*slice)[:index] // 移除最后一个元素 + return lastElement, true +} + +func SonicApiDataToStruct(data interface{}, structInterFace interface{}) (dataStruct interface{}, err error) { + bytes, err := sonic.Marshal(data) + if err != nil { + return nil, err + } + err = sonic.Unmarshal(bytes, &structInterFace) + return structInterFace, err +} + +func ContainsString(slice []string, s string) bool { + for _, item := range slice { + if item == s { + return true + } + } + return false +} + // 判断切片是否包含指定字符串 func SliceInStr(s string, slice []string) bool { for _, v := range slice { diff --git a/config/config.go b/config/config.go index 4db996c..9730e69 100644 --- a/config/config.go +++ b/config/config.go @@ -22,6 +22,7 @@ type Config struct { Debug bool `toml:"Debug"` PrometheusCollectEnable bool `toml:"PrometheusCollectEnable"` SkyWalkingOapServer string `toml:"SkyWalkingOapServer"` + TimeOut int64 `toml:"TimeOut"` Log config.LogConfig `toml:"Log"` Redis config.RedisConfig `toml:"Redis"` Mns config.MnsConfig `toml:"AliMns"` diff --git a/go.mod b/go.mod index 59112ea..cc9e3a3 100644 --- a/go.mod +++ b/go.mod @@ -6,8 +6,10 @@ require ( gitee.com/chengdu_blue_brothers/openapi-go-sdk v0.0.2 github.com/BurntSushi/toml v0.4.1 github.com/Shopify/sarama v1.19.0 + github.com/ZZMarquis/gm v1.3.2 github.com/ahmetb/go-linq/v3 v3.2.0 github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible + github.com/bytedance/sonic v1.10.2 github.com/forgoer/openssl v1.6.0 github.com/gin-gonic/gin v1.7.7 github.com/go-pay/gopay v1.5.103 @@ -23,6 +25,7 @@ require ( github.com/qit-team/snow-core v0.1.28 github.com/qit-team/work v0.3.11 github.com/robfig/cron v1.2.0 + github.com/spf13/cobra v1.2.1 github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271 github.com/swaggo/gin-swagger v1.3.3 github.com/swaggo/swag v1.7.9 @@ -50,6 +53,8 @@ require ( github.com/beorn7/perks v1.0.1 // indirect github.com/buger/jsonparser v1.1.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect + github.com/chenzhuoyu/iasm v0.9.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/eapache/go-resiliency v1.1.0 // indirect @@ -76,10 +81,12 @@ require ( github.com/google/uuid v1.3.0 // indirect github.com/hetiansu5/accesslog v1.0.0 // indirect github.com/hetiansu5/cores v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.13.6 // indirect + github.com/klauspost/cpuid/v2 v2.2.6 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible // indirect github.com/lestrrat-go/strftime v1.0.5 // indirect @@ -98,10 +105,12 @@ require ( github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a // indirect github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5 // indirect github.com/sirupsen/logrus v1.8.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect github.com/syndtr/goleveldb v1.0.0 // indirect github.com/tidwall/gjson v1.12.1 // indirect github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.6 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.1 // indirect @@ -113,6 +122,12 @@ require ( golang.org/x/sync v0.7.0 // indirect golang.org/x/sys v0.22.0 // indirect golang.org/x/text v0.16.0 // indirect + golang.org/x/arch v0.6.0 // indirect + golang.org/x/crypto v0.17.0 // indirect + golang.org/x/net v0.17.0 // indirect + golang.org/x/sync v0.1.0 // indirect + golang.org/x/sys v0.15.0 // indirect + golang.org/x/text v0.14.0 // indirect golang.org/x/time v0.1.0 // indirect golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect diff --git a/go.sum b/go.sum index 077bb7f..1bf415f 100644 --- a/go.sum +++ b/go.sum @@ -58,6 +58,8 @@ github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWX github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/ZZMarquis/gm v1.3.2 h1:lFtpzg5zeeVMZ/gKi0gtYcKLBEo9XTqsZDHDz6s3Gow= +github.com/ZZMarquis/gm v1.3.2/go.mod h1:wWbjZYgruQVd7Bb8UkSN8ujU931kx2XUW6nZLCiDE0Q= github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/agiledragon/gomonkey/v2 v2.3.1 h1:k+UnUY0EMNYUFUAQVETGY9uUTxjMdnUkP0ARyJS1zzs= github.com/agiledragon/gomonkey/v2 v2.3.1/go.mod h1:ap1AmDzcVOAz1YpeJ3TCzIgstoaWLA6jbbgxfB4w2iY= @@ -110,6 +112,10 @@ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kB github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= +github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE= +github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -117,6 +123,13 @@ github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= +github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= +github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= @@ -380,6 +393,7 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= @@ -460,6 +474,10 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= +github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -683,9 +701,11 @@ github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJ github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= @@ -695,6 +715,8 @@ github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5J github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -702,6 +724,7 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5 github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= @@ -725,6 +748,8 @@ github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhso github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= github.com/ugorji/go v1.2.6/go.mod h1:anCg0y61KIhDlPZmnH+so+RQbysYVyDko0IMgJv0Nn0= @@ -787,6 +812,9 @@ go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.6.0 h1:S0JTfE48HbRj80+4tbvZDYsJ3tGv6BUU3XxyZ7CirAc= +golang.org/x/arch v0.6.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -1002,6 +1030,7 @@ golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211213223007-03aa0b5f6827/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= @@ -1388,7 +1417,9 @@ modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= modernc.org/z v1.0.1/go.mod h1:8/SRk5C/HgiQWCgXdfpb+1RvhORdkz5sw72d3jjtyqA= modernc.org/z v1.2.19/go.mod h1:+ZpP0pc4zz97eukOzW3xagV/lS82IpPN9NGG5pNF9vY= modernc.org/z v1.2.20/go.mod h1:zU9FiF4PbHdOTUxw+IF8j7ArBMRPsHgq10uVPt6xTzo= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o=