javax.crypto.BadPaddingException: Message is larger than modulus
Have anyone experienced this issue? Please help me out.
The code of the off card side:
Code: Select all
// Text to send
byte [] s = {(byte) 'H', (byte) 'i'};
RSAPublicKeySpec pubKeySpec;
KeyFactory keyFactory = null;
PublicKey pubKey = null ;
Cipher cipher = null;
// Get the data from the apdu
byte[] publicKeyMessage = apdu.getDataOut();
byte[] modulusArray = new byte [64];
// Get the modulus from the public key sent in the apdu
for (int i=0; i<64; i++){
modulusArray[i] = publicKeyMessage[i+2];
}
byte[] exponentArray = new byte [3];
// Get the modulus from the public key sent in the apdu
for (int i=0; i<3; i++){
exponentArray[i] = publicKeyMessage[i+68];
}
BigInteger modulus = new BigInteger(modulusArray);
BigInteger exponent = new BigInteger(exponentArray);
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
keyFactory = KeyFactory.getInstance("RSA");
// Build the public Key by means of the modulus and exponent specs
pubKey = keyFactory.generatePublic(pubKeySpec);
// Indicate the cipher to use the pubKey which has just been built
cipher.init(Cipher.ENCRYPT_MODE,pubKey);
byte[] p = new byte[64];
// Encrypt with the public key
cipher.doFinal(s, 0, s.length, p, 0);
Part of the applet code:
Code: Select all
// In the constructor:
...
RSACipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1,false);
...
//In the process method:
...
buffer = apdu.getBuffer();
byte [] buf = null;
// Get the encoded message
short numBytes = apdu.setIncomingAndReceive();
// Copy to a aux buffer
Util.arrayCopy(buf, ISO7816.OFFSET_CDATA, buffer, (short)0, numBytes);
// Initialize the cipher and decrypt to send the plain text again
RSACipher.init(PrivateKeyRSAEnc,Cipher.MODE_DECRYPT);
RSACipher.doFinal(buf,(short)0,numBytes,buffer,(short)0);
apdu.setOutgoingAndSend((short) 0, numBytes);
...