Thursday, August 27, 2015

RSA Encryption/Decryption for Longer Strings

Previously we did see how we can encrypt/decrypt messages using RSA public/private keys here.
But it seems that there is a limit to the actual message that can be encrypted/decrypted using the method described there and that is based on the key length being used while generating the KeyPair.

The limit is seen as for RSA n bit key length , encryption limit = n/8 - 11
and for decryption , limit = n/8

So for RSA 1024 bit, max (1024/8 -11) = 117 bytes can be encrypted, and 128 bytes can be decrypted.
Similarly, for RSA 2048 bit, max (2048/8 -11) = 245 bytes can be encrypted and 256 bytes can be decrypted at a time.

So if one tries to use perform "RSAEncryption(publickey , message) , where if the message length is more than 117 (for 1024 bit RSA) or 245 (for 2048 bit RSA), then it turns out that the encryption will fail.
Same happens if one tries to perform "RSADecryption(privatekey , encryptedMessage)" ,  where if the encrypted message length is more than 128(for 1024 bit RSA) or 256 (for 2048 bit RSA), then the decryption will fail as well.


Does that mean long strings cannot be encrypted/decrypted by using RSA?

No.In case you want to encrypt/decrypt a message whose size is more than the limit specified as above, it needs to be handles separately rather than the approach used in previous post.
It has to be divided in block sizes based on the limit specified above, and then encryption/decyption can be performed on that block size.

Encrypting Long Message using N bit RSA


int KEY_LENGTH = N;(change it to key length used for Generating Keys i.e 1024/2048)

byte[] perfomRSAEncryption(PublicKey publicKey , byte[] message) {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE , publicKey);
int  limit = KEY_LENGTH/8 -11;
int position = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while(position < message.length) {
if(message.length - position < limit)
limit = message.length - position;
 byte[] data = cipher.doFinal(message , position , limit);
byteArrayOutputStream.write(data);
position += limit;
}

return byteArrayOutputStream.toByteArray();
}

Decrypting Long Message using N bit RSA


int KEY_LENGTH = N;(change it to key length used for Generating Keys i.e 1024/2048)

byte[] perfomRSADecryption(PublicKey publicKey , byte[] encryptedMessage) {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE , publicKey);
int  limit = KEY_LENGTH/8;
int position = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while(position < encryptedMessage.length) {
if(encryptedMessage.length - position < limit)
limit = encryptedMessage.length - position;
 byte[] data = cipher.doFinal(encryptedMessage , position , limit);
byteArrayOutputStream.write(data);
position += limit;
}

return byteArrayOutputStream.toByteArray();