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?

6
  • How are you generating the keys? Mar 25, 2018 at 14:00
  • @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())
    – CipherX
    Mar 25, 2018 at 14:27
  • why not just use the secp256k1 C library instead. You can still compile with cgo.
    – rny
    Apr 10, 2018 at 3:02
  • 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 lib
    – trung
    Jul 1, 2019 at 18:01
  • @trung is there a public repository where your modified x509 package can be found? Jun 11, 2020 at 11:57

2 Answers 2

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.

1
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.