0

I have the following code. I expected the console output to be 32 (bytes), but it's actually a lot longer. Why is that? Can I trim that down?

        ECDsaCng keyPair = new ECDsaCng(256);

        byte[] privateKey = keyPar.ExportECPrivateKey();

        //This will be 165 bytes
        Console.WriteLine(privateKey.Length);

This doesn't makes sense to me, since as I understand both the public and private keys should be exactly 32 bytes long. I found this other question which helped me a bit, but I don't understand why we need to stores keys in formats.

Can't I just get the private key as a 32 bytes long byte array? What do I need a format for?

  • Often keys are represented in text, not binary, for portability's sake. Check the format your `ECDsaCng()` gives you. – vonbrand Aug 19 '21 at 21:35
  • The Elliptic Curve Private Key (ECPrivateKey) Structure is discussed in [rfc 5915](https://datatracker.ietf.org/doc/html/rfc5915). – 500 - Internal Server Error Aug 19 '21 at 21:52
  • 1
    Keys can have different formats. `ExportECPrivateKey()` exports the key in SEC1 format, DER encoded. What you seem to want is the raw private key (32 bytes). Try `ECParameters ecParams = keyPair.ExportParameters(true)`. `ecParams.D` will then give you the raw private key as `byte[]`. – Topaco Aug 19 '21 at 21:54
  • Thank you @Topaco, that's exactly what I wanted. I have two other questions, if you'd be so kind. Firstly, I noticed that ecParams.Q does not return a byte array like D does, but rather a ECPoint object. Can I also get a public key "raw"? Secondly, how do I recreate a ECDsaCng key pair from a raw private key? Do I have to format it? – Bruno Rocha Aug 20 '21 at 00:39
  • 1
    1. yes, concatenate x and y coordinate of the point in a 64 bytes `byte[]` (with an additional leading `0x04`, also called _uncompressed_ key). 2. import the raw key (`ImportParameters()`). Please note that the comments are not for additional questions, so please ask a new question (if such a question does not already exist). – Topaco Aug 20 '21 at 06:58

0 Answers0