Page 1 of 1
RSA encryption algorithm
Posted: Mon Jul 11, 2016 1:54 am
by Bruninoit
I want to do RSA encryption & decryption in my applet. And my java card supports T=0 protocol. So can I send the data in an APDU command and also to get the encrypted data in the same APDU's response? Must I write two different commands to send the data for encryption and get the encrypted data?
Re: RSA encryption algorithm
Posted: Tue Jul 12, 2016 1:55 am
by wousim
For T=0 protocol, you can not receive the data in the same APDU response. You should send GET RESPONSE command to get the data.
It's the limitation of T=0 protocol.
Re: RSA encryption algorithm
Posted: Tue Jul 12, 2016 4:50 am
by Bruninoit
Thanks for your reply.
I also have another question. Here is section of my code. But it can't be able to work. It always threw exception. Could you point me where I made mistake?
Code: Select all
//In constructor
cipherRSA = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
//In Process Method
short len = apdu.setIncomingAndReceive(); // This is the amount of data read from the OS.
while (len < lc)
{
len += apdu.receiveBytes(len);
}
case ENCRYPT_HASH_INS:
encryptHash(apdu, len);
break;
case GET_ENCRYPT_HASH_INS:
getEncryptedHash(apdu);
break;
/*********************************************************************/
public void encryptHash( APDU apdu, short length)
{
byte [] buffer = apdu.getBuffer();
cipherRSA.init(rsa_PrivateCrtKey, Cipher.MODE_ENCRYPT);
short cipherLength = cipherRSA.doFinal(buffer, buffer[ISO7816.OFFSET_CDATA], length, buffer, buffer[ISO7816.OFFSET_CDATA]);
encyrtedHash = JCSystem.makeTransientByteArray(cipherLength, JCSystem.CLEAR_ON_RESET);
Util.arrayCopyNonAtomic(buffer, buffer[ISO7816.OFFSET_CDATA], encyrtedHash, (short) 0, length);
}
/*********************************************************************/
public void getEncryptedHash(APDU apdu)
{
apdu.setOutgoing();
apdu.setOutgoingLength((short)encyrtedHash.length );
apdu.sendBytesLong(encyrtedHash, (short)0, (short)(encyrtedHash.length));
}
Re: RSA encryption algorithm
Posted: Wed Jul 13, 2016 1:50 am
by Tarantino
There are some problems in your code.
Try the below code. This code will encrypt your data and send the response in one APDU.
Code: Select all
//In constructor
cipherRSA = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
//In Process Method
short len = apdu.setIncomingAndReceive(); // This is the amount of data read from the OS.
while (len < lc)
{
len += apdu.receiveBytes(len);
}
case ENCRYPT_HASH_INS:
encryptHash(apdu, len);
break;
/*********************************************************************/
public void encryptHash( APDU apdu, short length)
{
byte [] buffer = apdu.getBuffer();
cipherRSA.init(rsa_PrivateCrtKey, Cipher.MODE_ENCRYPT);
short cipherLength = cipherRSA.doFinal(buffer, ISO7816.OFFSET_CDATA, length, buffer, ISO7816.OFFSET_CDATA);
apdu.setOutgoing();
apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, cipherLen)
}