Java Smart Card - Reading Scosta Smart Card

2019-08-12 15:55发布

问题:

I am trying to read Indian Governments Standard 'Scosta' smart card through java smartcardio the code I am using is

package com.example.smartcardreader;

import java.util.List;

import javax.smartcardio.ATR;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;

public class SmartCardReader {

 public static void main(String[] args) {

        try{

            // 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
            CardTerminal terminal = terminals.get(0);

            // establish a connection with the card
            Card card = terminal.connect("*");
            System.out.println("card: " + card);

            // get the ATR
            ATR atr = card.getATR();
            byte[] baAtr = atr.getBytes();

            System.out.print("ATR = 0x");
            for(int i = 0; i < baAtr.length; i++ ){
                System.out.printf("%02X ",baAtr[i]);
            }

            CardChannel channel = card.getBasicChannel();
            byte[] cmdApduGetCardUid = new byte[]{
                        (byte)0xFF, (byte)0xCA, (byte)0x00, (byte)0x00, (byte)0x00};

            ResponseAPDU respApdu = channel.transmit(
                                                new CommandAPDU(cmdApduGetCardUid));

            if(respApdu.getSW1() == 0x90 && respApdu.getSW2() == 0x00){

                byte[] baCardUid = respApdu.getData();

                System.out.print("Card UID = 0x");
                for(int i = 0; i < baCardUid.length; i++ ){
                    System.out.printf("%02X ", baCardUid [i]);
                }
            }

        card.disconnect(false);

        } catch (CardException e) {
            e.printStackTrace();
        }
    }

}

I am using eclipse IDE for development in Mac machine. When I run this code, it gives me exception as it is not able to read Terminals. I have got a USB Card Reader and have also inserted smart card into it. Could you please point out where exactly am I going wrong. Thanks in advance.

回答1:

It may be unrelated to your problem but package javax.smartcardio seems to be seriously broken on Mac OS X with 64-bit version of java7. You can find more information in this blog post and this bug report. You can also take a look at open source project jnasmartcardio that tries to solve the issues of javax.smartcardio package.