gitee.com/zhaochuninhefei/gmgo@v0.0.31-0.20240209061119-069254a02979/ecdsa_ext/ecdsa_ext_test.go (about) 1 // Copyright (c) 2023 zhaochun 2 // gmgo is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 package ecdsa_ext 10 11 import ( 12 "crypto/elliptic" 13 "crypto/rand" 14 "crypto/sha256" 15 "encoding/hex" 16 "fmt" 17 "gitee.com/zhaochuninhefei/zcgolog/zclog" 18 "testing" 19 ) 20 21 func TestPrivateKey_Sign(t *testing.T) { 22 zclog.Level = zclog.LOG_LEVEL_DEBUG 23 24 privateKey, err := GenerateKey(elliptic.P256(), rand.Reader) 25 if err != nil { 26 t.Fatal(err) 27 } 28 29 msg := "花有重开日, 人无再少年" 30 digest := sha256.Sum256([]byte(msg)) 31 fmt.Printf("msg: %s\n", msg) 32 fmt.Printf("digest hex: %s\n", hex.EncodeToString(digest[:])) 33 34 sign, err := privateKey.Sign(rand.Reader, digest[:], nil) 35 if err != nil { 36 t.Fatal(err) 37 } 38 fmt.Printf("sign hex: %s\n", hex.EncodeToString(sign)) 39 40 pubKey, ok := privateKey.Public().(*PublicKey) 41 if !ok { 42 t.Fatal("PublicKey类型强转失败") 43 } 44 valied, err := pubKey.EcVerify(digest[:], sign, nil) 45 if !valied { 46 t.Fatal("验签失败") 47 } 48 fmt.Println("验签成功") 49 }