licel / jcardsim

https://jcardsim.org
224 stars 123 forks source link

ALG_RSA_PKCS1 returns incorrect length of data on decryption #91

Closed petrs closed 8 years ago

petrs commented 8 years ago

Problem: Decryption by PKCS#1 RSA engine returns always 245 bytes even when smaller amount of data was inserted for encryption. Data itself are correctly decrypted.

Version used: jcardsim-2.2.2-all.jar

Code fragment to replicate issue:

public void testJCardSimRSADecryptBug() throws Exception {
  KeyPair keyPair = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
  keyPair.genKeyPair();
  RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();

  Cipher rsaEngine = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
  rsaEngine.init(publicKey, Cipher.MODE_ENCRYPT);

  byte[] buffer = new byte[256];
  short dataLen = 16;
  Util.arrayFillNonAtomic(buffer, (short) 0, dataLen, (byte) 1);
  short encLen = rsaEngine.doFinal(buffer, (short) 0, dataLen, buffer, (short) 0);
  assert(encLen == 256);
  // For RSA2048, data len is 16, but when decrypted back, we will get 245 bytes
  rsaEngine.init(privateKey, Cipher.MODE_DECRYPT);
  short decLen = rsaEngine.doFinal(buffer, (short) 0, encLen, buffer, (short) 0);
  assert(decLen == dataLen);
}
petrs commented 8 years ago

At least I hope it should return length used for encryption (but not 100% sure)

petrs commented 8 years ago

Current sources do not exhibit this error - I'm closing this issue as duplicate to issue #82