This is my first question here, so I hope that I am providing enough information to be able to get some kind of resolution to this (smallish?) problem I’m having with a (IMO) very basic public key crypting/decrypting problem.
I’ve tried to follow examples, and I’ve read through APIs to try and figure out what is wrong, but so far I haven’t been able to come up with an answer to why the decryption fails with such a basic test…
I have printed out the hexes of all the stuff I transfer between the client and the server, and they seem to be identical. I’ve tried to use different paddings, and ciphers, but none seem to work.
The codes from the two programs (I’ve edited out the non-essential printouts):
Server code:
RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
PublicKey pk = kp.getPublic();
PrivateKey pri = kp.getPrivate();
InputStream in = csocket.getInputStream();
OutputStream out = csocket.getOutputStream();
DataInputStream dis = new DataInputStream(in);
DataOutputStream dos = new DataOutputStream(out);
// write getEncoded().length
dos.writeInt(pk.getEncoded().length);
// write key
byte[] public_key = pk.getEncoded();
for (int x=0;x<public_key.length;x++) {
dos.writeByte(public_key[x]);
}
dos.flush();
// read enc length
int len=dis.readInt();
byte[] data = new byte[len];
// read enc stuff
System.out.println("Read data:");
for (int x=0;x<len;x++) {
data[x]=dis.readByte();
}
// decrypt
byte [] decrypted = null;
try { cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, pri);
decrypted = cipher.doFinal(new String(data).getBytes());
} catch (Exception e) { e.printStackTrace(); }
Client:
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
DataInputStream dis = new DataInputStream(in);
DataOutputStream dos = new DataOutputStream(out);
// Read key length
int len = dis.readInt();
// Read key
byte[] public_key = new byte[len];
byte[] tmp = new byte[1];
for (int x = 0; x<len; x++) {
public_key[x] = dis.readByte();
}
try {
keySpec = new X509EncodedKeySpec(public_key);
keyFactory = keyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(keySpec);
} catch (Exception e) { e.printStackTrace(); }
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "IBMJCE");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// crypt string
data = cipher.doFinal(new String("Encrypt this").getBytes());
} catch (Exception e) { e.printStackTrace(); }
// write data.length
dos.writeInt(data.length);
// write encrypted data
for (int x=0; x<data.length;x++) {
dos.writeByte(data[x]);
}
dos.flush();
The answer to this problem was: Learn to read your own code, and keep track of what you’ve done… Sorry for wasting your time :/