I have written a java card applet to RSA encrypt incoming data with private key and send it out again.
Here is my code:
package test;
import javacard.framework.*;
import javacard.security.*;
import javacardx.crypto.Cipher;
public class test extends Applet
{
private static byte[] Hash = new byte[32];
private static byte[] Sign = new byte[256];
private static short hash_len = 0;
private static short sign_len = 0;
MessageDigest mDigest = MessageDigest.getInstance(MessageDigest.ALG_SHA_256,false);
Cipher rsaCipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
KeyPair rsaKey = new KeyPair(KeyPair.ALG_RSA,KeyBuilder.LENGTH_RSA_2048);
RSAPublicKey rsaPubKey = (RSAPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_2048, false);
public static void install(byte[] bArray, short bOffset, byte bLength)
{
new test().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
}
public void process(APDU apdu)
{
if (selectingApplet())
{
return;
}
byte[] buf = apdu.getBuffer();
switch (buf[ISO7816.OFFSET_INS])
{
case (byte)0x00: // generate keypair
rsaKey.genKeyPair();
break;
case (byte)0x01: // get public key
apdu.setIncomingAndReceive();
rsaPubKey = (RSAPublicKey) rsaKey.getPublic();
rsaPubKey.getModulus(buf, (short) 0);
apdu.setOutgoingAndSend((short) 0, (short) 256);
break;
case (byte)0x03: //encrypt by private key
short len = apdu.setIncomingAndReceive();
mDigest.reset();
hash_len = mDigest.doFinal(buf, (short) ISO7816.OFFSET_CDATA, len, Hash, (short)0);
rsaCipher.init(rsaKey.getPrivate(), Cipher.MODE_ENCRYPT);
sign_len = rsaCipher.doFinal(Hash, (short) 0, hash_len, Sign, (short)0);
Util.arrayCopy(Hash, (short)0, buf, (short)0, hash_len);
apdu.setOutgoingAndSend((short) 0, hash_len);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
}
I make keys successfully, but when I try to do the encryption, 6F 00
is returned in line sign_len = rsaCipher.doFinal(Hash, (short) 0, hash_len, Sign, (short)0);
.
Now my first question is How can I find out the meaning of 6F 00
SWs, i.e. How to handle run-time exceptions in my code and my second question is how to fix it and what is the problem? Where am I mistaken? (I am using java card kit 3.0.4.)