Hello,
I have a RSA encrypt methods that seems to work but when the input data is bigger that 117 bytes (for a 1024 key) and 245 bytes (for a 2046 key) the doFinal method throws a CryptoException.ILLEGAL_USE exception. How Is the clear data length that I can encrypt "at once" related to the RSA key length ?
Here is a sample code:
private void encryptRSATest() {
try {
KeyPair rsaKey = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1024);
rsaKey.genKeyPair();
Cipher rsaCipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
// check
if (rsaKey == null) {
ISOException.throwIt(SW_RSA_KEY_NOT_INITIALIZED);
}
// check
if (rsaCipher == null) {
ISOException.throwIt(SW_RSA_CIPHER_NOT_INITIALIZED);
}
// public key for encryption
RSAPublicKey pubKey = (RSAPublicKey) rsaKey.getPublic();
if (!pubKey.isInitialized()) {
ISOException.throwIt(SW_RSA_PUB_KEY_NOT_INITIALIZED);
}
// generate random data to decrypt
short OUT_BUFF_LEN = 1024;
short IN_BUFF_LEN = 118;
byte[] clearBuffOut = new byte[IN_BUFF_LEN];
byte[] encBuffOut = new byte[OUT_BUFF_LEN];
// just generate some random data to encrypt
RandomData random = RandomData.getInstance(RandomData.ALG_PSEUDO_RANDOM);
random.generateData(clearBuffOut, OFFSET_ZERO, (short) IN_BUFF_LEN);
// encrypt
rsaCipher.init(pubKey, Cipher.MODE_ENCRYPT);
short encSize = rsaCipher.doFinal(clearBuffOut, OFFSET_ZERO, IN_BUFF_LEN, encBuffOut, OFFSET_ZERO);
}
catch (CryptoException e) {
ISOException.throwIt(e.getReason());
}
}
This code throws the excpetion. If the IN_BUFF_LEN is 117 it works.
When I use the
rsaCipher.update instead of
doFinal, I can encrypt any data size up to 128 byte (for 1024 key) and up to 256 (for 2048 key). The documentation of [Cipher.update()|http://www.cs.ru.nl/~woj/javacardapi221/javacardx/crypto/Cipher.html] says
In addition, if the input data length is not block aligned (multiple of block size) then additional internal storage may be allocated at this time to store a partial input data block.
So, if I want to use only the doFinal, how am I suppose to "align" the data correctly ?
What am I doing wrong ?
Thanks in advance.
regards,
Tex