Raghu
Raghu

Reputation: 3091

Why does public key blob contains key type and key length in big endian format in .net framework 4.7?

I wrote following code to extract ECDH public key blob:

        var curve = ECCurve.NamedCurves.nistP256;
        ECDiffieHellman ecdh = ECDiffieHellman.Create(curve);

        var bytes = ecdh.PublicKey.ToByteArray();
        Console.WriteLine($"Public Key (byte length with format info): {bytes.Length}");

        var hexString = BitConverter.ToString(bytes).Replace("-", string.Empty);
        Console.WriteLine($"Public Key (hex with format info): {hexString}");

I got following output:

The first 4 bytes (key type) are 45434B31 (in hex format). This appears to be in big endian format where as this MSDN link indicates that it should be in little endian format, which dictates that these 4 bytes should be 314B4345 (again, as shown in this link). The link also uses "magic", instead of "key type". The next 4 bytes are 20000000 (in hex format) appears to be in the little endian format (as the above link says).

Is there a logical explanation for why key type is formatted as big endian? Or am I missing something here?

Upvotes: 0

Views: 1579

Answers (1)

bartonjs
bartonjs

Reputation: 33266

The first 4 bytes (key type) are 45434B31 (in hex format).

That would be 0x45434B31 (Big Endian interpretation), or 0x314B4345 (Little Endian interpretation). 0x314B4345 (LE) matches the nistP256 entry in your linked page.

Your question title indicates you believe that the length was stored big endian, but your question body you say it seems to be little endian. LE is correct. 20000000 is 0x00000020 (LE), or "32 byte fields". 32 bytes is 256 bits, which matches the expected answer for nistP256.


Note that you really don't want to use this blob format. The NIST P-256, 384, and 521 curves got distinct "magic" values, but the new Windows 10 additional curves all report under 0x504B4345 (BCRYPT_ECDH_PUBLIC_GENERIC_MAGIC). The curve name has to be carried externally.

The right answer on .NET for importing and exporting key values is the ECParameters struct via the ExportParameters and ImportParameters methods.

Upvotes: 1

Related Questions