/*
Config memory dumper for Atmel Cryptomemory smart cards, works with ISO7186 compliant reader enumerated at '0'.
Do whatever you want with this, I take no responsibility for whatever happens.
*/
import javax.smartcardio.*;
import java.util.*;

public class main {
	
	static CardTerminal reader;
	
	public static void main(String[] args) throws Exception {
		
		// show the list of available terminals
        TerminalFactory factory = TerminalFactory.getDefault();
        List<CardTerminal> terminals = factory.terminals().list();
        System.out.println("Terminals: " + terminals);
        
        // get the first terminal
        reader = terminals.get(0);

        // wait for card insertion (10 sec timeout)
        System.out.println("Waiting for insertion...");
        if(!reader.waitForCardPresent(10000))
        	System.out.println("No card inserted, timed out. (10 seconds)");
        System.out.println("");
        	
        // establish a connection with the card, show card details
        Card card = reader.connect("T=0");
        System.out.println("card: " + card);
        CardChannel channel = card.getBasicChannel();
        System.out.println("");

        // get and display card answer to reset
        ATR cardATR = card.getATR();
        System.out.println("Answer to reset: " + cardATR.getBytes() + " Hex: " + getHexString(cardATR.getBytes()));
        System.out.println("");

        dumpConfigMemory(channel);
	}
	
	public static String getHexString(byte[] b) throws Exception {
		  String result = "";
		  for (int i=0; i < b.length; i++) {
		    result +=
		          (Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ) + " ");
		  }
		  return result;
	}
	
	public static void dumpConfigMemory(CardChannel chan) throws Exception{
		
		int addr = 0;
		ResponseAPDU response;
		
		while(addr <= 232){
			CommandAPDU read1 = new CommandAPDU(0,0xb6,0, addr, 8);
			
			response = chan.transmit(read1);
			
			System.out.println("$" + Integer.toHexString(addr) + " " + getHexString(response.getBytes()));
			
			addr = addr + 8;
		}
		
	}

}
