Reputation: 191
I'm trying to encryt/decrypt using RSAEngine library at bouncy castle, with a 2048 bit length key. I'm able to create the keys, store in different files and get from the files, but when I decrypt an image it makes something that I don't know that the file decrypted is not shown correctly.Files are created correctly,and I think the problem is at processBlock method while encrypting and/or decrypting.The code is the following to encrypt:
InputStream clearTextFile;
FileOutputStream textFileProcessed=new FileOutputStream(fileName);
//getKey is a method I implemented and works correctly
RSAKeyParameters key=getKey(keyFileName);
RSAEngine rsaEngine=new RSAEngine();
rsaEngine.init(true,key);
clearTextFile=new FileInputStream(nameClearTextFile);
byte[] bytesReaded;
int nBytesReaded;
int inputBlockSize=rsaEngine.getInputBlockSize();
do
{
bytesReaded = new byte[inputBlockSize];
nBytesReaded=clearTextFile.read(bytesReaded);
if(nBytesReaded>-1)
{ //This is for the last block if it's not 256 byte length
if(nBytesReaded<inputBlockSize)
{
byte[] temp=new byte[nBytesReaded];
for(int i=0;i<nBytesReaded;i++)
{
temp[i]=bytesReaded[i];
}
byte[] encryptedText=rsaEngine.processBlock(temp,0,nBytesReaded);
textFileProcessed.write(encryptedText);
}
else
{
byte[] encryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);
textFileProcessed.write(encryptedText);
}
}
}while(nBytesReaded>-1);
textFileProcessed.flush();
textFileProcessed.close();
textFileProcessed.close();
And to decrypt:
InputStream encryptedTextFile=new FileInputStream(nameOfFile);
OutputStream decryptedTextFile=new FileOutputStream(nameOfFile);
RSAKeyParameters key=getKey(nameKeyFile);
RSAEngine rsaEngine=new RSAEngine();
rsaEngine.init(false,key);
byte[] bytesReaded;
int nBytesReaded;
int inputBlockSize=rsaEngine.getInputBlockSize();
do
{
bytesLeidos = new byte[inputBlockSize];
nBytesReaded=encryptedTextFile.read(bytesReaded);
if(nBytesReaded>-1)
{
byte[] decryptedText=rsaEngine.processBlock(bytesReaded,0,inputBlockSize);
decryptedTextFile.write(decryptedText);
}
}while(nBytesReaded>-1);
decryptedTextFile.flush();
decryptedTextFile.close();
encryptedTextFile.close();
Thanks in advance
Upvotes: 4
Views: 2552
Reputation: 561
RSAEngine does not add padding, you will lose any leading zeros in your data blocks as a result. You need to use one of the encoding modes available as well.
I'd recommend using a symmetric key algorithm as well and just using RSA to encrypt the symmetric key. It will be a lot faster, and depending on your data, safer as well.
Regards,
David
Upvotes: 2
Reputation: 12985
I think you need to change this line:
if(nBytesReaded>1)
to this
if(nBytesReaded>-1)
And change this in the decypt part, maybe:
rsaEngine.init(false,clave);
to this
rsaEngine.init(false,key);
But there may be more. You aren't encrypting the whole input if the last block isn't full size.
Upvotes: 1