Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Public key different after sent over socket
    primarykey
    data
    text
    <p>I'm trying to send a public key over a socket connection in Java. While I'm very conscious Java provides SSL functionality for this sort of activity, this is a uni assignment; I cannot use the Java implementation.</p> <p>The server encodes its public key and transmits it to the client via socket connection. When the client receives the key and decodes it, it appears different. Not only this, the data received by the client appears different to that transmitted by the server. I believe this is giving me problems when I attempt to then encrypt a user name and password using this key.</p> <p>The problem can be reproduced with the following code:</p> <p>Client:</p> <pre><code>public class TestClient { /** * @param args */ public static void main(String[] args) { final int sPort = 4321; Socket sock = null; Key serverPubKey = null; BufferedReader clientIn = null; // Initialise server connection try{ sock = new Socket(InetAddress.getLocalHost(), sPort); clientIn = new BufferedReader(new InputStreamReader(sock.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host."); System.exit(1); } catch (IOException e) { System.out.println("No I/O"); System.exit(1); } // Get server pub key try{ int len = Integer.parseInt(clientIn.readLine()); byte[] servPubKeyBytes = new byte[len]; sock.getInputStream().read(servPubKeyBytes,0,len); System.out.println(servPubKeyBytes); X509EncodedKeySpec ks = new X509EncodedKeySpec(servPubKeyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); serverPubKey = kf.generatePublic(ks); System.out.println(serverPubKey.getEncoded()); } catch (IOException e) { System.out.println("Error obtaining server public key 1."); System.exit(0); } catch (NoSuchAlgorithmException e) { System.out.println("Error obtaining server public key 2."); System.exit(0); } catch (InvalidKeySpecException e) { System.out.println("Error obtaining server public key 3."); System.exit(0); } } } </code></pre> <p>Server:</p> <pre><code>public class TestServer { public static void main(String[] args) { final int servPort = 4321; final int RSAKeySize = 1024; final String newline = "\n"; Key pubKey = null; ServerSocket cServer = null; Socket cClient = null; PrintWriter cOut = null; // Initialise RSA try{ KeyPairGenerator RSAKeyGen = KeyPairGenerator.getInstance("RSA"); RSAKeyGen.initialize(RSAKeySize); KeyPair pair = RSAKeyGen.generateKeyPair(); pubKey = pair.getPublic(); } catch (GeneralSecurityException e) { System.out.println(e.getLocalizedMessage() + newline); System.out.println("Error initialising encryption. Exiting.\n"); System.exit(0); } // Initialise socket connection try{ cServer = new ServerSocket(servPort); cClient = cServer.accept(); cOut = new PrintWriter(cClient.getOutputStream(), true); } catch (IOException e) { System.out.println("Error initialising I/O.\n"); System.exit(0); } // Send public key try { cOut.println(pubKey.getEncoded().length); System.out.println(pubKey.getEncoded()); cClient.getOutputStream().write(pubKey.getEncoded()); cClient.getOutputStream().flush(); } catch (IOException e) { System.out.println("I/O Error"); System.exit(0); } } } </code></pre> <p>This may be as simple as informing me my key is not X509 encoded, however this appears to be the way a key is recovered from a file (also read as bytes) so I can't understand why it won't work?</p> <p>Thanks very much in advance for any help/suggestions.</p> <p>Edit: problem solved, see Jeffrey's response. Modified (working) code posted as response.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. COWhy does your code have statements like "System.out.println(pubKey.getEncoded())"? PrintStream.println doesn't do anything special for byte[], so that will just print something like "[B@10b62c9" (meaning roughly "a byte[] at memory location 0x010B62C9"). I ask because you say that "the data received by the client appears different to that transmitted by the server", and I hope that the above statements aren't how you determined that.
      singulars
    2. CO@ruakh "and I hope that the above statements aren't how you determined that" unfortunately that's exactly what I was doing. I'm nearly a java virgin, actually, I had assumed it was doing some magical type casting into a char array or a string, would "new String(pubKey.getEncoded())" help me ascertain whether the sent/received data were the same? As far as I'm aware the byte array may not be able to be encoded correctly, but if they're equal I'll at least be able to roughly assume that's the case and try encrypting my user/pw again.
      singulars
    3. COI'd recommend "System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(pubKey.getEncoded()))", which uses the JDK 1.6 DatatypeConverter class (hat-tip to Sii below) to convert each byte into two hexadecimal digits. Otherwise you'll be printing bytes to your console that aren't ASCII print characters -- hard to compare, and hard on your ears if the alert/bell/beep character is in there!
      singulars
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload