I'm writing a program where I send bytes of a key from a keypair that I created over an output socket and use them to recreate the key on the other side. Server:
KeyPairGenerator dsaKeyPairGenerator =
KeyPairGenerator.getInstance("DSA");
dsaKeyPairGenerator.initialize(1024);
KeyPair dsakeyPair = dsaKeyPairGenerator.generateKeyPair();
PrivateKey dsaPrivate = dsakeyPair.getPrivate();
PublicKey dsaPublic = dsakeyPair.getPublic();
byte[] dsaPublicbytes = dsaPublic.getEncoded();
clientSocket.getOutputStream().write(dsaPublicbytes.length);
clientSocket.getOutputStream().write(dsaPublicbytes);
Client:
int dsalength = clientSocket.getInputStream().read();
byte[] dsaPublicbytes = new byte[dsalength];
clientSocket.getInputStream().read(dsaPublicbytes);
X509EncodedKeySpec dsaspec = new X509EncodedKeySpec(dsaPublicbytes);
KeyFactory dsakeyFactory = KeyFactory.getInstance("DSA");
PublicKey dsaKey = dsakeyFactory.generatePublic(dsaspec);
However, on this line I get an error:
PublicKey dsaKey = dsakeyFactory.generatePublic(dsaspec);
The trace for the error itself:
Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException: Detect premature EOF
at sun.security.provider.DSAKeyFactory.engineGeneratePublic(DSAKeyFactory.java:119)
at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
at Client.main(Client.java:36)
I have researched and I've seen that the EOF occurs because there aren't enough bytes to create the key, which leads me to believe that it is a problem with how I am sending the bytes. Am I sending the bytes incorrectly?