Use secp256k1 in Go
Asked Answered
A

2

6

I'm trying to use the elliptic curve secp256k1 in Go with the library "crypto/x509". After the key pair generation, I obtain respectively the public key pubKey and the private key privKey. After that, I want to generate a certificate that include the public key, but before I want to store the private key in a .pem file:

keyDer, err := x509.MarshalECPrivateKey(privKey)
    if err != nil {
        log.Fatalf("Failed to serialize ECDSA key: %s\n", err)
    }

but when I try to marshal an EC private key into ASN.1, DER format and to compile the code, I receive an error that said:

Failed to serialize ECDSA key: x509: unknown elliptic curve

In this case it's necessary for me to work with that particular curve, so I cannot change to prime256v1 or ''similar curve''. Is there a solution that permits to add the support for secp256k1 in crypto/x509 library, or another way/suggestion?

Ardine answered 25/3, 2018 at 11:19 Comment(6)
How are you generating the keys?Zygapophysis
@VictorOliveira I'm working with the library: github.com/btcsuite/btcutil/hdkeychain. I'm generating the key as: privKey, err := hdkeychain.NewMaster(seed, &chaincfg.MainNetParams) //EC Private Key sKey, err := privKey.ECPrivKey() and finally as the question's code: keyDer, err := x509.MarshalECPrivateKey(privKey.ToECDSA())Ardine
why not just use the secp256k1 C library instead. You can still compile with cgo.Pure
I used this github.com/sour-is/koblitz, then clone the Golang x509 package by starting from x509.ParseCertificate() and resolving all dependencies. Noted: i'm not affiliated in anyway with the libPrince
@Prince is there a public repository where your modified x509 package can be found?Librettist
@GaëtanLehmann I gave up the implementation as it's too complex with many invasive changes. Please do express your use cases in github.com/golang/go/issues/32874 so Go team can prioritizePrince
C
4

There is no secp256k1 curve type in go.

How did you created key-pairs?

I faced this problem. In my case, I used the go-ethereum package to create this curve type. So, I used the same package's function to parse the key.

So you have to use same package's specified function to parse the key-pair.

This x509.MarshalECPrivateKey(privKey) will only helps to Marshal go's standard curve type.

Candelariacandelario answered 20/8, 2020 at 6:54 Comment(1)
be aware that this go-ethereum implementation of secp256k1 is not fully supported without cgo enabled github.com/ethereum/go-ethereum/blob/v1.11.5/crypto/secp256k1/…Fredericafrederich
P
3

You can use secp256k1 module by decred/dcrd. It is currently used by btcsuite/btcd repo.

Pierro answered 7/4, 2022 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.