I have written a little chat and messages are objects like
{type="message",sender="userA",content="plaintextmessage",recipient="userB"}
that are sent to the server who spread it to all enrolled users. I want to encrypt the plaintextmessage-part that the message object looks like
{type="message",sender="userA",content="bHJg67&GghjGZuf/zdu=",recipient="userB"}
I have build my RSA keypair on both - server and client.
KeyPair keyPair = buildKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
Then i encode the servers public key to a byte array and this array to a base64 encoded string and send it to the client.
byte[] encodedPublicKey = publicKey.getEncoded();
String b64PublicKey = Base64.getEncoder().encodeToString(encodedPublicKey);
Both, client and server, have implemented the functions
public static byte[] encrypt(PublicKey othersPubKey, String message) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, othersPubKey);
return cipher.doFinal(message.getBytes());
}
public static byte[] decrypt(PrivateKey privateKey, byte [] encrypted) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encrypted);
}
When i try to encrypt a message on the client, send it to the server and decrypt it there i get the error
javax.crypto.IllegalBlockSizeException: Data must not be longer than 512 bytes
Does that means that this encryption method is nout suitable for my messages? I found Java/JCE: Decrypting "long" message encrypted with RSA. Is that my new goal?