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.