Search code examples
javanetwork-programmingrsaencryption-asymmetric

RSA encryption and decryption of a long message in java


I want to use java standard library, and as much as I know, its functions inputs are limited. So I implemented two methods to this purpose. Here they are:

private byte[] RSAenc(String in) throws Exception {
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, privKey);
    int l = in.length();

    byte[] part;
    byte[] result = new byte[(int)(64*java.lang.Math.ceil(l/20.0))];
    int i = 0;
    while(i*20+20<l) {
        part = c.doFinal(in.substring(i*20,i*20+19).getBytes("UTF-8"));
        System.arraycopy(part, 0, result, i*64, part.length);
        i = i+1;
    }
    part = c.doFinal(in.substring(i*20,l-1).getBytes("UTF-8"));
    System.arraycopy(part, 0, result, i*64, part.length);
    return result;

}

private String RSAdec(byte [] in) throws Exception {
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.DECRYPT_MODE, privKey);

    String result = "";
    byte[] part = new byte[64];
    int l = in.length;
    int i = 0;
    while(i+64<=l) {
        System.arraycopy(in, i, part, 0, part.length);
        result = result + new String(c.doFinal(part), "UTF-8");
        i= i+64;
    }
    return result;
}

They work in this manner: for encryption I break the string to at most, 20 size substrings, and then use the Cipher to encrypt them. For decryption, I break byte array to 64 byte blocks, and apply Cipher decryption to them. Is there already a function which do this? Or at least is there a neater solution? How safe is my approach? Is encryption result length (result.length) always 64 on all distributions of JRE?

Thanx,


Solution

  • RSA is suited to key encipherment, not bulk data encryption.

    Instead of encrypting messages with RSA, most protocols generate a key for a symmetric cipher, like AES, and encrypt the message with that. Then, RSA is used to encrypt that symmetric key so that only the message recipient can recover it. The RSA-encrypted symmetric key is sent with the AES-encrypted message to the recipient.