0
votes

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?

1
Yeah, you don't use asymmetric encryption for encrypting generic data.Kayaman

1 Answers

1
votes

Yes, it is called a hybrid cryptosystem. Even then, you may want to understand about the Bleichenbacher attack, the use of authenticated encryption, how to gain trust in a public key etc.

So your goal is either to study the field in much more detail or to learn a lot less about deploying TLS 1.2 or 1.3. Because it takes a lot of details to implement transport mode security.

If you want to continue, at least take a look at RSA in OAEP mode and AES in GCM mode.