xikimay
xikimay

Reputation: 167

How to sign a message with an ECDSA string privateKey

I'm trying to sign a message with an ECDSA privateKey but with a type string. The problem is in order to sign the message I need to use the "Sign" method from the ecdsa package.

func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)

This method can only take a PrivateKey type. How can I convert my string private key to this type? Or is another method available ?

Upvotes: 1

Views: 1995

Answers (1)

Marc
Marc

Reputation: 21075

You can parse DER-encoded elliptic curve private keys using the standard library's x509.ParseECPrivateKey.

derKey := []byte(keyString)
privKey, err := x509.ParseECPrivateKey(derKey)
if err != nil {
  panic(err)
}
signedMsg, err := privKey.Sign(randReader, msg, otps)

If your key is in PEM format, you must first decode it using pem.Decode:

var block *pem.Block
if block, _ = pem.Decode([]byte(keyString)); block == nil {
    panic("expected pem block")
}
privKey, err := x509.ParseECPrivateKey(block.Bytes)
// etc... the rest is the same

Upvotes: 1

Related Questions