For an academic network application, I'd like to set up an RSA key exchange between 2 virtual machines. I am using Crypto++ to generate the RSA::PublicKey
, and I must now send it within a custom layer-2 frame (the packet will be crafted with libcrafter
).
The thing is, I have no idea of how write the key in the network, such as the receiver, sniffing the packet, is able to re-build, somehow, the RSA::PublicKey
.
I tried to save it raw in a string, but as they say here, the PublicKey
class contains other data, then simply the raw key (data that I don't need). nevertheless, I manage to success that, but at the reception I can't simply rebuild the PublicKey...
Could it be possible, somehow, to concatenate the modulus, the primes and the public exponent, in order to rebuild the publicKey
at the reception?
Sender
Here is the code I use at the sender. It's the essential lines, but my program has other functionality, and it would be too long to post it entirely here).
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, 3072);
RSA::PublicKey publicKey(privateKey);
cout << ">> Key generated" <<endl;
/* Convert key to string then to const char* */
std::string publicKeyString;
publicKey.BEREncode( StringSink(publicKeyString).Ref() );
const char * publicKeyChar = publicKeyString.c_str();
cout <<"key size : "<<publicKeyString.size()<< endl;
/* Send Packet */
Crafter::RawLayer type1("K");
Crafter::RawLayer key_send(publicKeyChar);
//Crafter::RawLayer key_send(publicKeyString.c_str(), publicKeyString.length());
Crafter::Packet packet_key (ether_header / type1 / key_send);
packet_key.Send(iface);
Receiver
And here is my attempt to recover the key.
/* Extract Payload */
PayloadLayer *payload_rcv = pack_recu.getLayerOfType<PayloadLayer>();
size_t payload_size = payload_rcv->getPayloadLen() ;
Crafter::byte *payload = payload_rcv->getPayload();
cout << ">> Public Key recieved"<<endl;
// Convert into RSA::PublicKey
stringstream ss;
for (int i=0; i< payload_size; i++)
ss << payload[i];
string payload_string = ss.str();
cout << "Payload Size: "<<payload_size<<endl;
cin.get();
StringSource stringSource(payload_string, true);
RSA::PublicKey publicKey2;
publicKey2.BERDecode(stringSource);
data->publicKey = publicKey2;
And here is the result of running the program:
terminate called after throwing an instance of 'CryptoPP::BERDecodeErr'
what(): BER decode error
I'm sure the error comes from the conversion from string to publicKey...
The BERDecode
function war originally thought to recover the key from a file...
Does anyone has a solution ? I think that sending apart all the elements to rebuild the key could be better, but I can't figure how to do it...