package com.cscn;

import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;

/**
 * @author liuww
 *
 */
public class XwSecurity extends Applet {

	//todo test
	public static final byte INS_PROCESS_DATA_TEST = (byte)0xE3;

	public static final byte INS_LOCATION_ENCRYPT = (byte)0xCA;

	public static final byte INS_STORE_KEY = (byte)0xE2;

//	public static final byte INS_INITIAL_UPDATE = (byte)0x50;
//
//	public static final byte INS_EXTERNAL_AUTH = (byte)0x82;

	private Method method;

	byte[] key_store_byte;

	public XwSecurity(byte[] bArray, short bOffset, byte bLength) {
		// TODO Auto-generated constructor stub
		method = new Method(); //todo new?
		// key store -> flash
		key_store_byte = new byte[120];

		register(bArray, (short)(bOffset + 1), bArray[bOffset]);
	}

	public static void install(byte[] bArray, short bOffset, byte bLength)
	{
		//todo new?
		// GP-compliant JavaCard applet registration
		new XwSecurity(bArray, bOffset, bLength);
	}

	public void process(APDU apdu)
	{
		// Good practice: Return 9000 on SELECT
		if(selectingApplet())
		{
			return;
		}

		if(method == null) {
			return;
		}

		byte[] buf = apdu.getBuffer();
		short off = ISO7816.OFFSET_CDATA;
		short len = apdu.setIncomingAndReceive();

		switch (buf[ISO7816.OFFSET_INS])
		{
//			case INS_INITIAL_UPDATE:
//				SecureChannel sc = GPSystem.getSecureChannel();
//				sc.processSecurity(apdu);
//				break;
//
//			case INS_EXTERNAL_AUTH:
//				sc = GPSystem.getSecureChannel();
//				sc.processSecurity(apdu);
//				break;


			//todo test
			case INS_PROCESS_DATA_TEST:
				method.testZuc256(apdu);
				break;


			case INS_LOCATION_ENCRYPT:
				len = method.locationEncryptZuc(buf, off, len, key_store_byte);
				apdu.setOutgoingAndSend(off, len);
				break;

			case INS_STORE_KEY:
				len = method.updateKey(buf, off, len, key_store_byte);
				apdu.setOutgoingAndSend(off, len);
				break;

			default:
				// good practice: If you don't know the INStruction, say so:
				ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
		}


	}
}