FISCO-BCOS / go-sdk

golang SDK of FISCO BCOS
Apache License 2.0
74 stars 58 forks source link

如何将go生成的非国密的账户私钥转为pem文件 #273

Closed wjbbig closed 7 months ago

wjbbig commented 7 months ago

如题,go的x509不支持secp256k1曲线,用其他方式虽然可以成功转为pem,但是sdk的LoadECPrivateKeyFromPEM方法无法解析,下面是我用的测试代码:

var (
    oidNamedCurveSecp256k1 = asn1.ObjectIdentifier{1, 3, 132, 0, 10}
    oidNamedCurveSm2p256v1 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
)

type secprivateKey struct {
    Version       int
    PrivateKey    []byte
    NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"`
    PublicKey     asn1.BitString        `asn1:"optional,explicit,tag:1"`
}

func genBcosAccount() (*ecdsa.PrivateKey, error) {
    privKey, err := crypto.GenerateKey()
    if err != nil {
        return nil, err
    }

    privateKey := make([]byte, (privKey.Curve.Params().N.BitLen()+7)/8)
    privBytes, err := asn1.Marshal(secprivateKey{
        Version:       1,
        PrivateKey:    privKey.D.FillBytes(privateKey),
        NamedCurveOID: oidNamedCurveSecp256k1,
        PublicKey:     asn1.BitString{Bytes: elliptic.Marshal(privKey.Curve, privKey.X, privKey.Y)},
    })
    if err != nil {
        return nil, fmt.Errorf("marshalling EC private key: %s", err)
    }
    file, err := os.OpenFile("abc.pem", os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return nil, fmt.Errorf("opening file: %s", err)
    }
    if err = pem.Encode(file, &pem.Block{
        Type:  "PRIVATE KEY",
        Bytes: privBytes,
    }); err != nil {
        return nil, fmt.Errorf("writing private key: %s", err)
    }

    return privKey, err
}