Hi,
I'm writing an application that is going to use RSA encryption/decryption.
I know that there are some problems with encrypting big arrays (error: input too large for RSA cipher), so I created my own function that's parsing the data before the encryption.
And know the problem - it seems that sometimes it works, and sometimes it doesn't.
I mean for the same input array I can get different result - everything goes well or I get
org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
And I really don't understand why it sometimes works just fine and sometimes (all the control data is the same -> commented system.outs) throws the exception.
Can anyone help?
Here is the code:
public static byte[] encrypt(byte[] data, CipherParameters key) {
System.out.println("<--------START--ECRYPTION---------->");
RSAEngine engine = new RSAEngine();
engine.init(true, key);
int blockSize = engine.getOutputBlockSize();
//System.out.println("blockSize:"+blockSize);
int numWholeBlocks = data.length / blockSize;
//System.out.println("numWholeBlocks:"+numWholeBlocks);
int sizeLastBlock = data.length % blockSize;
//System.out.println("sizeLastBlock:"+sizeLastBlock);
int numBlocks;
if (sizeLastBlock > 0) {
numBlocks = numWholeBlocks + 1;
} else {
//when the size is a multi of a blockSize
numBlocks = numWholeBlocks;
sizeLastBlock=blockSize;
}
//System.out.println("numBlocks:"+numBlocks);
//System.out.println("sizeLastBlock:"+sizeLastBlock);
byte[] ciphertext = new byte[numBlocks * blockSize];
//System.out.println("ciphertext.length:"+ciphertext.length);
byte[] aux;
int WN = numBlocks - numWholeBlocks;
for (int i = 0; i < numWholeBlocks; i++) {
//System.out.println("blockSize: "+blockSize);
//System.out.println("i*blockSize: "+i*blockSize);
aux = engine.processBlock(data, i * blockSize, blockSize);
System.arraycopy(aux, 0, ciphertext, i * blockSize, blockSize);
}
for (int i = 0; i < WN; i++) {
aux = engine.processBlock(data, i * blockSize, sizeLastBlock);
System.arraycopy(aux, 0, ciphertext, numWholeBlocks * blockSize, blockSize);
}
System.out.println("<---------END--ECRYPTION----------->");
return ciphertext;
}