首页 > 解决方案 > 在golang中解组特定曲线的EC点

问题描述

我正在尝试解析 EC 点

04410478ed041c12ddaf693958f91f1174e0c790b2ff580ddca39bc2a4f78ad041dc379aaefe27cede2fa7601f90e3f397938ee53268564e346ac7a58aac8c28ca5415

到具有以下代码的 ecdsa.PublickKey 结构:

    x, y := readECPoint(elliptic.P256(), point)
    if x == nil || y == nil {
        panic("unable to parse the public key")
    }
    pubKey := &ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}

    pubKeyBytes := elliptic.Marshal(curve, pubKey.X, pubKey.Y)

在 github 上浏览时,我注意到了这段代码,这对我来说很有意义:

func readECPoint(curve elliptic.Curve, ecpoint []byte) (*big.Int, *big.Int) {
    x, y := elliptic.Unmarshal(curve, ecpoint)
    if x == nil {
        // http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_ftn1
        // PKCS#11 v2.20 specified that the CKA_EC_POINT was to be store in a DER-encoded
        // OCTET STRING.
        var point asn1.RawValue
        asn1.Unmarshal(ecpoint, &point)
        if len(point.Bytes) > 0 {
            x, y = elliptic.Unmarshal(curve, point.Bytes)
        }
    }
    return x, y
}

我尝试的其他事情是:

curve := new(secp256k1.BitCurve)
x, y := curve.Unmarshal(point)

然而,所有这些以前的代码总是返回 x=nil 和 y=nil

我知道密钥对是在具有比特币曲线的 HSM 中生成的

asn1.ObjectIdentifier 1.3.132.0.10

我是否缺少其他东西来正确解析比特币/以太坊曲线中的 EC 点?

标签: goethereumbitcoinelliptic-curveecdsa

解决方案


第一个代码片段似乎是错误的,因为elliptic.P256() 返回了一个实现 NIST P-256 的曲线,也称为 secp256r1 或 prime256v1。但是比特币/以太坊曲线使用的是secp256k1 格式,这是不同的。

我建议使用go-etherium包来创建 secp256k1 曲线。

我还发现你的钥匙有问题。它的长度为 67,但公钥的大小必须为 65(参见源代码)。正如 Topaco 指出的那样,前两个字节可能是长度为 65 字节(0x41)的八位字节字符串(0x04)的 ASN.1 编码,因此实际密钥从第 3 个字节开始。

我编写了这个使用 go-etherium 解析密钥的最小示例:

package main

import (
    "encoding/hex"
    "fmt"

    "github.com/ethereum/go-ethereum/crypto/secp256k1"
)

func main() {
    c := *secp256k1.S256()
    data, err := hex.DecodeString("04410478ed041c12ddaf693958f91f1174e0c790b2ff580ddca39bc2a4f78ad041dc379aaefe27cede2fa7601f90e3f397938ee53268564e346ac7a58aac8c28ca5415")
    if err != nil {
        panic(err)
    }
    x, y := c.Unmarshal(data[2:])
    fmt.Printf("%v\n%v\n", x, y)
}

输出:

54696312948195154784868816119600719747374302831648955727311433079671352319031
69965364187890201668291488802478374883818025489090614849107393112609590498325

推荐阅读