Search code examples
pythonc++crypto++diffie-hellmanpython-cryptography

Diffie-Hellman key exchange between Crypto++ and Python


Consider the Diffie-Hellman key exchange between client and server, where the client application is written in c++ and the back-end is written in python. The client application uses Crypto++ lib for crypto stuff and Python uses cryptography.

Here client application part where private and public key generate

//domain parameters
OID CURVE = secp256k1();
AutoSeededX917RNG<AES> rng;
ECDH < ECP >::Domain dhA(CURVE);

// application private and publik key
SecByteBlock privA(dhA.PrivateKeyLength()), pubA(dhA.PublicKeyLength());
std::string privB64(R"(P3VfVpnSYcKQWX+6EZOly2XKy6no4UAB0cQhjBfyBD4=)");
privA.Assign(reinterpret_cast<const byte*>(FromB64(privB64).c_str()), dhA.PrivateKeyLength());
dhA.GeneratePublicKey(rng, privA, pubA);

// serializa public key into integer
Integer intPub;
intPub.Decode(pubA.BytePtr(), pubA.SizeInBytes());
std::string ret;
intPub.DEREncode(CryptoPP::StringSink(ret));
std::cout << ToB64(ret);// the output is loaded into python

Now the question is that I don't know how to deserialize the public key into python EllipticCurvePublicKey. When I use cryptography.hazmat.primitives.serialization.load_der_public_key() I'm getting

ValueError: Could not deserialize key data

Does anyone try to implement Diffie-Hellman key exchange between Crypto++ and Python using those two libraries?


Solution

  • The issue was when serialized data in some way was transferred to backend how to recover it with Python EllipticCurvePublicKey type interface. Even if I decide to use protobuf the same question would arise.

    But now I found the solution I'll put it here if anyone also will encounter this issue.

    As I find out there is no interface to directly load Python EllipticCurvePublicKey object from Crypto++ SecByteBlock serialized object (which is representing the Diffie-Hellman public key in this scope).

    To do this we need to convert public key into elliptic curve point and the serialize each coordinate of point (which is a big integer) in the way as you can see in this code snipped:

    CryptoPP::DL_GroupParameters_EC<ECP> params(CURVE);    
    CryptoPP::ECPPoint p = params.DecodeElement(pubA.BytePtr(), true);
    std::cout << CryptoPP::IntToString(p.x) << std::endl;// this will be send to backend
    std::cout << CryptoPP::IntToString(p.y) <<std::endl;
    

    To recover the two integers (x and y coordinates of the point) in the Python code as a DH public key you need to do the following

    # assuming that the x and y values are from client side 
    x = 109064308162845536717682288676453496629093274218806834681903624047410153913758
    y = 63162707562199639283552673289102028849183508196715869820627148926667819088660
    peer_public_key =cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1()).public_key(default_backend())