问题
I've written a program to encrypt 10
bytes random number using an RSA public key on my Java Card. The random number is generated each time that the card receives that APDU command, and as the related cipher object block size is 2048 bit in my applet, I append 242 bytes of 0x00
at the end of this 10
byte random number to make it 256
bytes length.
The problem is that sometimes the response is a Crypto Exception with 05
value. As you know and as JC API documents mentioned:
0x05
= ILLEGAL_USEpublic static final short ILLEGAL_USE
This reason code is used to indicate that the signature or cipher algorithm does not pad the incoming message and the input message is not block aligned.
As the input length is fixed in my applet, I can't resolve my problem!
Here is the related part of my applet:
protected final void getEncChallenge(APDU apdu) {
random.generateData(generatedChall, (short) 0, (short) 10);
initAsymCipher(ENTITY_BOB, MODE_ENC);
Util.arrayCopy(generatedChall, (short) 0, transientData, (short) 0, (short) 10);
Util.arrayFillNonAtomic(transientData, (short) 10, (short) 246, (byte) 0x00);
rsaCrypto(transientData, persistentData);
apdu.setOutgoing();
apdu.setOutgoingLength((short) 256);
apdu.sendBytesLong(persistentData, (short) 0, (short) 256);
}
protected final void rsaCrypto(byte[] inData, byte[] outData) {
try{
asymCipher.doFinal(inData, (short) 0, (short) 256, outData, (short) 0);
}catch(CryptoException e){
short reason = e.getReason();
ISOException.throwIt((short)(0x6d00 | reason));
}
}
And here is the response:
transientData ---> APDU Response
---------------------------------
80 ..(Eight Random Bytes).. BD ..(246 bytes of "0x00").. ---> OK (i.e. 256 byte encrypted data)
EO ..(Eight Random Bytes).. 64 ..(246 bytes of "0x00").. ---> 6D05
02 ..(Eight Random Bytes).. B3 ..(246 bytes of "0x00").. ---> OK
CB ..(Eight Random Bytes).. 35 ..(246 bytes of "0x00").. ---> 6D05
17 ..(Eight Random Bytes).. 97 ..(246 bytes of "0x00").. ---> OK
0C ..(Eight Random Bytes).. 0C ..(246 bytes of "0x00").. ---> OK
D3 ..(Eight Random Bytes).. 91 ..(246 bytes of "0x00").. ---> 6D05
86 ..(Eight Random Bytes).. E2 ..(246 bytes of "0x00").. ---> OK
C2 ..(Eight Random Bytes).. 23 ..(246 bytes of "0x00").. ---> 6D05
Does anyone have any idea what's wrong with my applet?
回答1:
You are padding at the wrong side. RSA works on big endian encoded numbers up to the modulus size. The usual padding mechanisms (which are required for the usual RSA security) work by left padding, to a value strictly smaller than the modulus.
So basically your padded challenge is seen as a encoded number, and when converted, it sometimes is larger than the modulus. When that happens the RSA routine won't accept it.
Padding the zero bytes to the left should fix this. Alternatively you could make sure that the highest order bit of the challenge is masked to zero (& 0x7F
).
来源:https://stackoverflow.com/questions/38059175/rsa-encrytion-throws-an-exception-intermittently-on-javacard