AES sample code
Posted: Mon Oct 24, 2016 11:24 pm
I am getting started with AES algorithm. Is there any guide or sample code for me to refer to?
thanks very much.
thanks very much.
JavaCardOS - JavaCardForum
http://www.javacardos.com/javacardforum/
http://www.javacardos.com/javacardforum/viewtopic.php?f=12&t=890
Code: Select all
package crypto_aes;
import javacard.framework.*;
import javacard.security.*;
import javacardx.crypto.*;
public class CryptoAES extends javacard.framework.Applet
{
//globals
AESKey aesKey;
Cipher cipherAES;
RandomData random;
static byte a[];
final short dataOffset = (short) ISO7816.OFFSET_CDATA;
//constructor
private CryptoAES (byte bArray[], short bOffset, byte bLength)
{
aesKey = (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);
cipherAES = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
a = new byte[ (short) 128];
random.generateData(a, (short)0, (short)128);
aesKey.setKey(a, (short) 0);
register(bArray, (short) (bOffset + 1), bArray[bOffset]);
}
//install
public static void install(byte bArray[], short bOffset, byte bLength)
{
new CryptoAES (bArray, bOffset, bLength);
}
public void process(APDU apdu)
{
byte[] buf = apdu.getBuffer();
if (selectingApplet())
{
return;
}
if (buf[ISO7816.OFFSET_CLA] != 0) ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
if (buf[ISO7816.OFFSET_INS] != (byte) (0xAA)) ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
switch (buf[ISO7816.OFFSET_P1])
{
case (byte) 0x01:
doAES(apdu);
return;
default:
ISOException.throwIt(ISO7816.SW_WRONG_P1P2);
}
}
private void doAES(APDU apdu)
{
byte b[] = apdu.getBuffer();
short incomingLength = (short) (apdu.setIncomingAndReceive());
if (incomingLength != 24) ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
//perform encryption and append results in APDU Buffer a[] automatically
cipherAES.init(aesKey, Cipher.MODE_ENCRYPT);
cipherAES.doFinal(b, (short) dataOffset, incomingLength, a, (short) (dataOffset + 24));
cipherAES.init(aesKey, Cipher.MODE_DECRYPT);
cipherAES.doFinal(b, (short) (dataOffset + 24), incomingLength, a, (short) (dataOffset + 48));
// Send results
apdu.setOutgoing();
apdu.setOutgoingLength((short) 72);
apdu.sendBytesLong(b, (short) dataOffset, (short) 72);
}
Code: Select all
a = new byte[ (short) 128];
random.generateData(a, (short)0, (short)128);
Code: Select all
// Buffers of short data type
short[] shortBuff = JCSystem.makeTransientShortArray((short) 1, JCSystem.MEMORY_TYPE_TRANSIENT_RESET);
... some other codes ...
cipherAES.doFinal(b, (short) (dataOffset + 24), incomingLength, a, (short) (dataOffset + 48));
// You do not need to calculate how many bytes to send out as this uses a short buffer object to hold the number of output bytes
apdu.setOutgoing();
apdu.setOutgoingLength((short) (shortBuff[0] & 0xFF));
apdu.sendBytesLong(b, (short) dataOffset, (short) (shortBuff[0] & 0xFF));