1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package main
import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "crypto/elliptic" "log" "fmt" "math/big" )
func newKeyPair3() (ecdsa.PrivateKey, []byte) {
curve := elliptic.P256()
private, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil { log.Panic(err) }
pubKey := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)
return *private, pubKey }
func main(){
privKey,pubkey := newKeyPair3()
hash := sha256.Sum256([]byte("跟着jonson老师实战区块链\n"))
r, s, _ := ecdsa.Sign(rand.Reader, &privKey, hash[:])
curve := elliptic.P256()
keyLen := len(pubkey)
x := big.Int{} y := big.Int{} x.SetBytes(pubkey[:(keyLen / 2)]) y.SetBytes(pubkey[(keyLen / 2):])
rawPubKey := ecdsa.PublicKey{curve, &x, &y}
if ecdsa.Verify(&rawPubKey, hash[:], r, s) == false { fmt.Printf("%s\n", "验证失败") }else{ fmt.Printf("%s\n", "验证成功") }
hash2 := sha256.Sum256([]byte("我要给你200愿\n"))
if ecdsa.Verify(&rawPubKey, hash2[:], r, s) == false { fmt.Printf("%s\n", "验证失败") }else{ fmt.Printf("%s\n", "验证成功") } }
|