0

Beacuse I know someone is going to tell me to use something else, I can't. This is for a uni project, and I gotta stick to these protocols.

I'll try and post all the relevant code.

First, on my main, I do this

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(512);
KeyPair pair = keyPairGen.generateKeyPair();

Then, I pass this pair to a thread

Thread sender = new Thread(new UDPSend(s, host, peers.get(peer), portData, sents, lock, condition, pair));

On sender, this happens

byte[] keyBuf = pair.getPublic().getEncoded();
DatagramPacket keyPacket = new DatagramPacket(keyBuf, keyBuf.length, InetAddress.getByName(peer), port);
ds.send(keyPacket);

On another thread, theres a receiver running that does this

byte[] keyBuf = new byte[1024];
DatagramPacket keyPacket = new DatagramPacket(keyBuf, keyBuf.length);
ds.receive(keyPacket);
byte[] keyBytes = keyPacket.getData();
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));

And here I get an exception: Invalid Key Spec.

The part that's really bugging me is it only happens sometimes. Sometimes it works. The first time I boot up the program it always works, but when I trigger it to do it again, it fails. Any help is appreciated.

Pedro Fernandes
  • 216
  • 1
  • 12
  • If something works unreliable and UDP is used than usually UDP is the problem as it is by definition unreliable. I would print all incoming UDP packets in hex form to see what is received e.g. because UDP packets can get fragmented if the are too large: https://stackoverflow.com/questions/38723393/can-udp-packet-be-fragmented-to-several-smaller-ones – Robert May 18 '20 at 16:15

1 Answers1

0

On my system I changed on receiver side the line

byte[] keyBytes = keyPacket.getData();

to

byte[] keyBytes = Arrays.copyOf(keyPacket.getData(), keyPacket.getLength());

The "keyPacket.getData()" method seems to serve the complete buffer (1024 byte long) and the method "keyPacket.getLenth()" provides the "real" data length.

Michael Fehr
  • 5,827
  • 2
  • 19
  • 40
  • thanks for the input, but by now I already tried that, still, same result... I'm going to do a workaround as I'm not excatly forced to share the key trough udp – Pedro Fernandes May 18 '20 at 19:36