0

I have web services implemented that comunicate between client and server with strings. The problem I'm getting is with the conversion of the encripted byte array to string since I can't convert it back to the original content on server side.

KeyPairGenerator keyGen;
keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();

String publicKeyPath = new String("publicKeys.txt");
publickey = key.getPublic()
byte[] pubEncoded = key.getPublic().getEncoded();
FileOutputStream fout = new FileOutputStream(publicKeyPath);
fout.write(pubEncoded);
fout.flush();
fout.close();

String privateKeyPath = new String("privateKeys.txt");
byte[] privEncoded = key.getPrivate().getEncoded();
fout = new FileOutputStream(privateKeyPath);
fout.write(privEncoded);
fout.flush();
fout.close();

cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

And on each method in client:

cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publickey); 
byte[] cipherText = cipher.doFinal(str.getBytes());
port.callX(chiperText.toString());

On server side:

cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] newPlainText = cipher.doFinal(arg.getBytes());

This gives the padding problem of "Data must start with a zero"

There is only one KeyPair generated, for debug, I tried to encrypt and decript on the same function, and the problem relies on the conversions from byte[] to String.

I don't really wan't to change the passing of arguments to other type since operations are auto generated and all code is to strings. I've tried with different "UTF-8" and "UTF-16Le" but none works :S

Any idea?

d0pe
  • 573
  • 4
  • 9
  • 23

1 Answers1

0

Encrypting data directly with asymmetric keys isnt a good idea and it does not work. RSA keys cannot encrypt data bigger than its key length. So, the right way of doing that would be to generate a symmetric key and encrypt the data with the symmetric key and inturn encrypt the symmetric key with the asymmetric key. So, you need to send the encrypted data and the encrypted key both to the other party.

If you try encrypting the data directly with the asymmetric key then your byte[] may not contain the correct data or it may contain nothing at all. This happens if your data is bigger than the key length. For data smaller the key length it works fine but not with bigger data.

Drona
  • 6,886
  • 1
  • 29
  • 35
  • it needs to be with assymetric keys, it's one of the requirements. Thing is, I managed to convert them from byte to string and back to normal but with "ISO-8859-1" now, the problem is that I can't pass it through webservices since it contains illegal characters :( – d0pe May 15 '12 at 10:53