Browse Source

增加SM2加解密,增加jwt

master v0.4.0
gz 7 months ago
parent
commit
55a671d281
7 changed files with 338 additions and 3 deletions
  1. +2
    -2
      ecb_test.go
  2. +5
    -1
      go.mod
  3. +68
    -0
      go.sum
  4. +128
    -0
      jwt.go
  5. +15
    -0
      jwt_test.go
  6. +82
    -0
      sm2.go
  7. +38
    -0
      sm2_test.go

+ 2
- 2
ecb_test.go View File

@ -15,9 +15,9 @@ func Test_TripleECBEncrypt(t *testing.T) {
func Test_TripleECBDecryptFromHex(t *testing.T) {
key := "7ejGP1WiZkgZ8VaIf6vBOBDFUnmByZiO" // 24字节的密钥
key = "99ef199ddd11ff93d6927f755fd2b108"
msg := "0a7d96e2459dfa37cd13b8611acb26dd9adf31016bdb93da0d25d6a8041005e6"
// msg = "38142e6afc57a2a70ccaebc906accdf050984102f405fb6b2edcea6f28feb646"
msg = "AD2A27C86D0E6C0499BEEFDD60675129"
data, err := TripleECBDecryptFromHex(key, msg)
t.Log(data)


+ 5
- 1
go.mod View File

@ -2,4 +2,8 @@ module git.tetele.net/tgo/crypter
go 1.14
require golang.org/x/crypto v0.18.0 // indirect
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect
github.com/tjfoc/gmsm v1.4.1 // indirect
golang.org/x/crypto v0.18.0 // indirect
)

+ 68
- 0
go.sum View File

@ -1,25 +1,72 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
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/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@ -33,7 +80,28 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

+ 128
- 0
jwt.go View File

@ -0,0 +1,128 @@
package crypter
import (
"errors"
"fmt"
"log"
"strconv"
"time"
"github.com/dgrijalva/jwt-go"
)
//JWT = JSON WEB TOKEN 是一个开放标准,用于作为json对象,在各个地方安全的传输信息
//此信息可以被验证和信任
func CreateJwtToken(client_id, client_secret string) (string, error) {
// Define the secret key used for signing the token
secretKey := []byte(client_secret)
// Create a new token with claims
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
// Set the issuer, issued at, and JWT ID claims
claims["iss"] = client_id
claims["iat"] = time.Now().Unix()
claims["jti"] = strconv.Itoa(time.Now().Nanosecond())
// log.Println(claims)
// Sign the token with the secret key
tokenString, err := token.SignedString(secretKey)
if err != nil {
log.Println("Error signing token:", err)
return "", err
}
return tokenString, nil
}
func VerifyToken(tokenString string, client_id, client_secret string, expire int64) (bool, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(client_secret), nil
})
// log.Println(token, token.Claims, err)
if token.Valid {
claims := token.Claims.(jwt.MapClaims)
if client_id != claims["iss"] {
return false, errors.New("invalid client_id")
}
iat := ToInt64(claims["iat"])
now := time.Now().Unix()
log.Println(iat, now)
if now-iat > expire || iat-now > expire {
return false, errors.New("invalid time")
}
return true, nil
} else if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return false, errors.New("Malformed token")
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
return false, errors.New("Expired token")
} else {
return false, errors.New("Invalid token")
}
} else {
return false, errors.New("Invalid token")
}
}
func CheckJwtToken(tokenString string, client_secret string) (jwt.MapClaims, bool, error) {
// Define the secret key used for verifying the token
secretKey := []byte(client_secret)
// jwt.DecodeSegment()
// Parse the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Check the signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return secretKey, nil
})
// Verify the token
if err != nil {
log.Println("Error parsing token:", err)
return nil, false, err
}
if token.Valid {
// log.Println("Token is valid!")
// Access the claims
claims := token.Claims.(jwt.MapClaims)
// log.Println("Issuer:", claims["iss"])
// log.Println("Issued At:", claims["iat"])
// log.Println("JWT ID:", claims["jti"])
return claims, true, nil
}
return nil, false, nil
}
func ToInt64(inter interface{}) int64 {
var value int64
switch inter.(type) {
case string:
value, _ = strconv.ParseInt(inter.(string), 10, 64)
case int:
value = int64(inter.(int))
case int64:
value = inter.(int64)
case float64:
value_int, _ := strconv.Atoi(fmt.Sprintf("%1.0f", inter))
value = int64(value_int)
case nil:
value = 0
case interface{}:
if _, ok := inter.(int64); !ok {
value = inter.(int64)
}
default:
log.Println("参数值类型错误", inter, "not in string|int|float64|interface|int64")
}
return value
}

+ 15
- 0
jwt_test.go View File

@ -0,0 +1,15 @@
package crypter
import (
"testing"
)
func Test_VerifyToken(t *testing.T) {
token := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI5NzRjNzM1NjFhZTU0MjczIiwiaWF0IjoxNzExNzA1MTgwLCJqdGkiOiI3YzUzNGEyNi1jOTVmLTQ3NmQtYThjYS1lY2FjYTMxN2I1NDQifQ.h9JOqQOPN-xzTD7X5YPlS6YyshcixV329lEo_sX8tGw"
secret := "0f82962e24be4274a3b852f2d5b26f7e"
client_id := "974c73561ae54273"
ret, err := VerifyToken(token, client_id, secret, 600)
t.Log(ret)
t.Log(err)
}

+ 82
- 0
sm2.go View File

@ -0,0 +1,82 @@
package crypter
import (
"encoding/hex"
"errors"
"log"
"strings"
"crypto/rand"
"fmt"
"github.com/tjfoc/gmsm/sm2"
"github.com/tjfoc/gmsm/x509"
)
func Sm2EncryptWithHexKey(message string, public_key string) (string, error) {
sm2PubKey, err := x509.ReadPublicKeyFromHex(public_key)
if err != nil {
fmt.Println("Error parsing SM2 public key:", err)
return "", err
}
// 待加密的数据
data := []byte(message)
// 使用SM2公钥加密数据
ciphertext, err := sm2.Encrypt(sm2PubKey, data, rand.Reader, sm2.C1C3C2)
if err != nil {
log.Println("Error encrypting data with SM2:", err)
return "", errors.New("Error encrypting data with SM2," + err.Error())
}
if err != nil {
log.Println("Error encrypting data with SM2:", err)
return "", errors.New("Error encrypting data with SM2")
}
return hex.EncodeToString(ciphertext), nil
// return base64.StdEncoding.EncodeToString(ciphertext), nil
}
func Sm2DecryptWithHexKey(message string, private_key string) (string, error) {
sm2PriKey, err := x509.ReadPrivateKeyFromHex(private_key)
if err != nil {
fmt.Println("Error parsing SM2 private key:", err)
return "", err
}
// 待加密的数据
data, err := hex.DecodeString(message) //base64.StdEncoding.DecodeString(message) //
if err != nil {
fmt.Println("Error base64 message:", err)
return "", err
}
// 使用SM2私钥加密数据
ciphertext, err := sm2.Decrypt(sm2PriKey, data, sm2.C1C3C2)
if err != nil {
log.Println("Error decrypting data with SM2:", err)
return "", errors.New("Error encrypting data with SM2:" + err.Error())
}
return string(ciphertext), nil
}
func CreateHexKey() (string, string, error) {
// 生成SM2密钥对
priv, err := sm2.GenerateKey(rand.Reader)
if err != nil {
return "", "", err
}
// 将私钥转换为PEM格式的字符串
privPem := x509.WritePrivateKeyToHex(priv)
pubPem := x509.WritePublicKeyToHex(priv.Public().(*sm2.PublicKey))
return strings.ToUpper(privPem), strings.ToUpper(pubPem), err
}

+ 38
- 0
sm2_test.go View File

@ -0,0 +1,38 @@
package crypter
import (
"testing"
)
func Test_Sm2EncryptWithHexKey(t *testing.T) {
publicKeyStr := "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEW8Jjr6PAAbt4CNLwy96IAFYqYzTYNXmFRP5WQIQHlVOyKwGt4mWvOp3cYIYLNPz4Zul+ssHGj6iIR5/g7/GPVQ=="
message := "Hello, SM2!"
// ret, err := Sm2Encrypt(message, publicKeyStr)
// //BB06ddYi5lZ375jb1SWVZz7TrohrDS2XBDxgbMSgK4/oltdKt7tZZ917uZ1BInmrjDhuYpgCXZ9Pm7MACv8jKBT2BeRYEa2bEoh5s9iu0pLkiEbCxEd0+rSQ7QzOTXjOuUMfv05abYImjg==
// t.Log(ret)
// t.Log(err)
publicKeyStr = "042CC19B64E0BD66F39636FD088CDB95B94FC0D6E8F859D6A3CE667EBEF27BAF0DC56EA45C8F48A9C820DB00D84445CF408A533986C2A26AF2A92C22C784A6F63E"
ret, err := Sm2EncryptWithHexKey(message, publicKeyStr)
t.Log(ret)
t.Log(err)
}
func Test_Sm2DecryptWithHexKey(t *testing.T) {
var private_key string = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgeCC1xjOtVEUPXf/sHWGamWnpV2GCJcFXDMNdjHoFXYegCgYIKoEcz1UBgi2hRANCAARbwmOvo8ABu3gI0vDL3ogAVipjNNg1eYVE/lZAhAeVU7IrAa3iZa86ndxghgs0/Phm6X6ywcaPqIhHn+Dv8Y9V"
// message := "BNw3kw95aBovbvkJQ5NgIQnfDP1xJwGHUii4LWTjmrxzE7zlXkh0Py8+K8XuMFnqJn+9n5VheFyCAwOPg1Iw4yB4CDyBW5hGOXDlXV0qe+iaSdRCFJYoz810HStXKKwRjHA1+L5FXHIU+Q=="
message := "04b45733bf34c3e11a52027e8f477ce107e3c5ce18e678583b849a05ac98d3bf50997e36539edf9e959a2b2aa3813037ce06da99fc13c5fc60741fce0a056af65abcfc0a3b1fc0969dcb29c8d609076a118fa72c8704f02c47faae45a5eea9dfa99e4e0a83a4954aa2eee089"
private_key = "4B906B75EB9979A1F2AB00AFC192F2E574451871A003D46B328F88D3EF487836"
ret, err := Sm2DecryptWithHexKey(message, private_key)
t.Log(ret)
t.Log(err)
}
func Test_CreateHexKey(t *testing.T) {
priv, pub, err := CreateHexKey()
t.Log(priv)
t.Log(pub)
t.Log(err)
}

Loading…
Cancel
Save