/**
 * 
 */
package com.cscn;

import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import org.globalplatform.GPSystem;
import org.globalplatform.SecureChannel;

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

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

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

	public static final byte INS_INITIAL_UPDATE = (byte)0x50;

	public static final byte INS_EXTERNAL_AUTH = (byte)0x82;
	
	private Method method;
	
	public XwSecurity(byte[] bArray, short bOffset, byte bLength) {
		// TODO Auto-generated constructor stub
		method = new Method();
		
		register(bArray, (short)(bOffset + 1), bArray[bOffset]);
	}

	public static void install(byte[] bArray, short bOffset, byte bLength)
	{
		// 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();
		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;
			
		case INS_PROCESS_DATA:
			method.processData(apdu);
			break;
			
		case INS_STORE_DATA:
			method.updateKey(apdu);
			break;
			
		default:
			// good practice: If you don't know the INStruction, say so:
			ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
		}
		

	}
}