首页 > 文章列表 > btcec库在验证secp256k1签名时使用了哪种验证方法?

btcec库在验证secp256k1签名时使用了哪种验证方法?

498 2025-03-19
问题内容

我正在使用 btcec 库在 Go 中处理 secp256k1 签名。不过我在官方文档中并没有找到明确的验证签名的方法。btcec 文档中有一个“验证签名”示例的链接,但似乎没有直接提供示例代码。

我想知道,btcec库中的哪个方法用于验证secp256k1签名?如果有人可以提供一个简单的代码示例,那就太好了。谢谢!


正确答案


给你;-)

https://github.com/btcsuite/btcd /blob/master/btcec/ecdsa/example_test.go

// This example demonstrates verifying a secp256k1 signature against a public
// key that is first parsed from raw bytes.  The signature is also parsed from
// raw bytes.
func Example_verifySignature() {
    // Decode hex-encoded serialized public key.
    pubKeyBytes, err := hex.DecodeString("02a673638cb9587cb68ea08dbef685c" +
        "6f2d2a751a8b3c6f2a7e9a4999e6e4bfaf5")
    if err != nil {
        fmt.Println(err)
        return
    }
    pubKey, err := btcec.ParsePubKey(pubKeyBytes)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Decode hex-encoded serialized signature.
    sigBytes, err := hex.DecodeString("30450220090ebfb3690a0ff115bb1b38b" +
        "8b323a667b7653454f1bccb06d4bbdca42c2079022100ec95778b51e707" +
        "1cb1205f8bde9af6592fc978b0452dafe599481c46d6b2e479")

    if err != nil {
        fmt.Println(err)
        return
    }
    signature, err := ecdsa.ParseSignature(sigBytes)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Verify the signature for the message using the public key.
    message := "test message"
    messageHash := chainhash.DoubleHashB([]byte(message))
    verified := signature.Verify(messageHash, pubKey)
    fmt.Println("Signature Verified?", verified)

    // Output:
    // Signature Verified? true
}