How to derive a symmetric key from ECDH shared secret? I am trying to implement the internal primitives of ECDH. Currently I'm able to multiply the receiver's public EC point with the sender's private key to arrive at the shared EC point. Next step is to input the x-coordinate of the shared point which is a bignum to a hashing function. The curve is secp521r1 so the shared x-coordinate is of size 66 bytes.

Question 1

What format must the x-coordinate bignum be converted to before hashing it? The other party is openssl.

Is something like below sufficient...

...
print_hex(hash_input_buffer, shared_x_coordinate_bignum_bytes, 66);
...

void print_hex(unsigned char* to, unsigned char* from, int len)
{
    for (int i = 0; i &lt; len; ++i)
    {
        sprintf((char*)to + (i * 2), "%02x", from[i]);
    }
}


OR

sprintf(hash_input_buffer, "%64x", shared_x_coordinate_bignum_bytes);


Question 2

If the hashing function is SHA-512 and I want to derive an AES-256 key from it, should I just take the first 32 bytes of the 64 byte hash output?
The general idea to derive keys from (ephemeral) Diffie-Hellman key agreement is to use a KBKDF - a key based key derivation function. KBKDFs are mostly ill defined with regards to what security requirements they adhere to. Fortunately creating a KBKDF isn't thought to be too hard. Using a cryptographically secure hash generally gets you a long way. You should however note that in that case the hash should not be vulnerable to timing- and other side channel attacks.
The input of a KBKDF or a hash is bits. Generally though only bytes are used as input. So you should be using the 66 bytes of the shared secret directly. Your conversion to hexadecimals likely already leaks side channel (timing) information. So the answer to the first question is: don't convert the x-coordinate at all.
You can indeed take any part of the SHA-512 hash as key. It is however more standard within the cryptographic community to take the first - leftmost - bytes of the resulting hash value. So that should answer question 2: just use the leftmost bytes as you're already doing.
If you want to be standards compliant and use a KBKDF then please take a look at HKDF.