Java: Public key different after sent over socket
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.
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 encr开发者_Python百科ypt a user name and password using this key.
The problem can be reproduced with the following code:
Client:
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);
}
}
}
Server:
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);
}
}
}
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?
Thanks very much in advance for any help/suggestions.
Edit: problem solved, see Jeffrey's response. Modified (working) code posted as response.
In real-world code, I strongly advise against making direct use of the cryptography classes in this way. If at all possible, use the Java Secure Socket Extension.
That said, the bug I see is that you're mixing InputStreamReader
access with a raw InputStream
underneath. The InputStreamReader
may read more bytes than you ask for in readLine
— it's written to pretty much assume it owns the underlying InputStream
and so can read ahead in buffered blocks.
To quote the javadoc:
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
It is possible to send the public key by object over socket for example we can write a class as Frame like below:
import java.io.Serializable;
public class Frame implements Serializable {
byte[] data;
}
in client side just define the Frame and socket and just write into it:
Frame frame = new Frame();
frame.data = thePublicKey.getEncoded();
toServer.writeObject(frame);
in the server side decode the public key:
Frame frame = fromClient.readObject();
byte[] pubKey = frame.data;
X509EncodedKeySpec ks = new X509EncodedKeySpec(pubKey);
KeyFactory = KeyFactory.getInstance("RSA");
thepublicKey = kf.generatePublic(ks);
Firstly, thanks everyone for all your help, it's very much appreciated! 12 hours to go before this is due and I was starting to get worried, smooth sailing from here I think :).
Anyway, the revised code:
Server:
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;
// 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();
} catch (IOException e) {
System.out.println("Error initialising I/O.\n");
System.exit(0);
}
// Send public key
try {
System.out.println(DatatypeConverter.printHexBinary(pubKey.getEncoded()));
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(pubKey.getEncoded().length);
cClient.getOutputStream().write(bb.array());
cClient.getOutputStream().write(pubKey.getEncoded());
cClient.getOutputStream().flush();
} catch (IOException e) {
System.out.println("I/O Error");
System.exit(0);
}
}
}
Client:
public class TestClient {
/**
* @param args
*/
public static void main(String[] args) {
final int sPort = 4321;
Socket sock = null;
Key serverPubKey = null;
// Initialise server connection
try{
sock = new Socket(InetAddress.getLocalHost(), sPort);
} 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{
byte[] lenb = new byte[4];
sock.getInputStream().read(lenb,0,4);
ByteBuffer bb = ByteBuffer.wrap(lenb);
int len = bb.getInt();
System.out.println(len);
byte[] servPubKeyBytes = new byte[len];
sock.getInputStream().read(servPubKeyBytes);
System.out.println(DatatypeConverter.printHexBinary(servPubKeyBytes));
X509EncodedKeySpec ks = new X509EncodedKeySpec(servPubKeyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
serverPubKey = kf.generatePublic(ks);
System.out.println(DatatypeConverter.printHexBinary(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);
}
}
}
Beside the mixing of Writers and OutputStreams that Jeffrey has explained, the following might also be problematic:
sock.getInputStream().read(servPubKeyBytes,0,len);
The JavaDoc for InputStream.read writes:
Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer. This method blocks until input data is available, end of file is detected, or an exception is thrown. If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b. Let k be the number of bytes actually read; these bytes will be stored in elements b[0] through b[k-1], leaving elements b[k] through b[b.length-1] unaffected.
That is, read()
may read less bytes than requested. If you know there are more bytes, you should call read
repeatedly until all data has been read, something like:
for (int p = 0; p < len; ) {
int read = in.read(servPubKeyBytes, p, len - p);
if (read == -1) {
throw new RuntimeException("Premature end of stream");
}
p += read;
}
精彩评论