JavacardOS will not accept order any more, please contact our partner Feitian online Store:
https://ftsafe.en.alibaba.com/index.html
https://ftsafe.en.alibaba.com/index.html
RSA in java card
Moderator: UNKNwYSHSA
RSA in java card
Does anyone have sample code for RSA encryption / decryption running on java card?
Re: RSA in java card
Maybe the code below will be helpful to you.
Code: Select all
public RSAEncDec(byte[] bArray,short bOffset,byte bLength){
outbuffer = new byte[128];
inbuffer = new byte[64];
cipherENC = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
cipherDEC = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
rsaPrivateKey = (RSAPrivateCrtKey)KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_CRT_PRIVATE, KeyBuilder.LENGTH_RSA_512, false);
rsaPublicKey = (RSAPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC, KeyBuilder.LENGTH_RSA_512, false);
kp = new KeyPair(KeyPair.ALG_RSA_CRT, (short)512);
kp.genKeyPair();
rsaPrivateKey = (RSAPrivateCrtKey)kp.getPrivate();
rsaPublicKey = (RSAPublicKey)kp.getPublic();
register();
}
public static void install(byte[] bArray, short bOffset, byte bLength) {
new RSAEncDec(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:
break;
case RSAENC:
encryptData(apdu);
break;
case RSADEC:
decryptData(apdu);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void encryptData(APDU apdu){
short length =0;
byte[] buffer = apdu.getBuffer();
byte incomingLength = (byte) (buffer[ISO7816.OFFSET_LC]);
if (incomingLength != 8)
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
Util.arrayFillNonAtomic(inbuffer, (short)0, (short)64, (byte)0);
Util.arrayFillNonAtomic(outbuffer,(short)0, (short)128, (byte)0);
Util.arrayCopy(buffer, (short)5, inbuffer, (short)0,incomingLength);
cipherENC.init(rsaPrivateKey, Cipher.MODE_ENCRYPT);
length = cipherENC.doFinal(inbuffer, (short)0, (short)incomingLength, outbuffer, (short)0);
Util.arrayCopy(outbuffer, (short)0, buffer, (short)0, length);
apdu.setOutgoingAndSend( (short)0, length);
}
private void decryptData(APDU apdu){
short length = 0;
byte[] buffer = apdu.getBuffer();
cipherDEC.init(rsaPublicKey, Cipher.MODE_DECRYPT);
length = cipherDEC.doFinal(outbuffer, (short)0, (short)64, outbuffer, (short)0);
Util.arrayCopy(outbuffer, (short)0, buffer, (short)0, length);
apdu.setOutgoingAndSend( (short)0, length);
}
Who is online
Users browsing this forum: Google [Bot] and 15 guests