Fabric案例会给Peer、User、Admin等节点生成公、私钥对。公、私钥分别如下图所示。
用上述公、私钥对签名并验证消息的示例代码如下。
package main import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/pem" "fmt" "io/ioutil" ) func main() { msg := "hello, world" hash := sha256.Sum256([]byte(msg)) msg2 := "Hello, world" hash2 := sha256.Sum256([]byte(msg2)) privBytes, _ := ioutil.ReadFile("./priv_sk") blkPriv, _ := pem.Decode(privBytes) fmt.Println("priv_sk type:", blkPriv.Type) key, _ := x509.ParsePKCS8PrivateKey(blkPriv.Bytes) ecdsaKey := key.(*ecdsa.PrivateKey) r, s, _ := ecdsa.Sign(rand.Reader, ecdsaKey, hash[:]) certBytes, _ := ioutil.ReadFile("./cert.pem") blkCert, _ := pem.Decode(certBytes) fmt.Println("cert.pem type:", blkCert.Type) cert, _ := x509.ParseCertificate(blkCert.Bytes) pubkey := cert.PublicKey.(*ecdsa.PublicKey) ok := ecdsa.Verify(pubkey, hash[:], r, s) fmt.Println("verify hash(shoule be true):", ok) ok = ecdsa.Verify(pubkey, hash2[:], r, s) fmt.Println("verify hash2(shoule be false):", ok) }编译并运行,如下所示。