Example #1
1
 private static TerminalFactory loadFactory(String pn, String type)
     throws NoSuchAlgorithmException {
   TerminalFactory tf = null;
   try {
     Class<?> cls = Class.forName(pn);
     Provider p = (Provider) cls.getConstructor().newInstance();
     tf = TerminalFactory.getInstance(type == null ? "PC/SC" : type, null, p);
   } catch (ClassNotFoundException
       | InstantiationException
       | IllegalAccessException
       | IllegalArgumentException
       | InvocationTargetException
       | NoSuchMethodException
       | SecurityException e) {
     throw new RuntimeException("Could not load " + pn, e);
   } catch (NoSuchAlgorithmException e) {
     if (e.getCause() != null) {
       Class<?> cause = e.getCause().getClass();
       if (cause.equals(java.lang.UnsupportedOperationException.class)) {
         throw new NoSuchAlgorithmException(e.getCause().getMessage());
       }
       if (cause.equals(java.lang.UnsatisfiedLinkError.class)) {
         throw new NoSuchAlgorithmException(e.getCause().getMessage());
       }
     }
     throw e;
   }
   return tf;
 }
Example #2
0
  public void ConnectToSmartCard() {
    try {
      TerminalFactory factory = TerminalFactory.getDefault();
      List<CardTerminal> terminals = factory.terminals().list();
      System.out.println("Terminals: " + terminals);
      // get the first terminal
      // CardTerminals.State.
      CardTerminal terminal = terminals.get(0);

      if (terminal.isCardPresent()) {
        JOptionPane.showMessageDialog(null, "Card is Present");
        this.terminal = terminal;
      } else {
        JOptionPane.showMessageDialog(null, "Card is absent.Connnect it in 5 secs\nWaiting...");
        terminal.waitForCardPresent(5000);
        JOptionPane.showMessageDialog(null, "Time is Up!\nBye!!!");
        return;
      }
      // establish a connection with the card
      Card card = terminal.connect("*");
      this.card1 = card;
    } catch (CardException ce) {

    }
  }
Example #3
0
  /**
   * Find and connect to a terminal, based on the preferences in TERMINAL_PREFERENCES
   *
   * @return a valid CardTerminal or halts the system if no match can be found
   */
  private void determineCardTerminalToUse() {
    try {
      synchronized (synchronizer) {
        // show the list of available terminals
        TerminalFactory factory = TerminalFactory.getDefault();
        List<CardTerminal> terminals = factory.terminals().list();

        System.out.println(
            "There are " + TERMINAL_PREFERENCES.size() + " possible terminal matches");
        System.out.println("There are " + terminals.size() + " terminals attached to this machine");

        for (int j = 0; j < TERMINAL_PREFERENCES.size(); j++) {
          String requiredTerminal = TERMINAL_PREFERENCES.get(j);
          System.out.println("Trying to attach to '" + requiredTerminal + "'");
          for (int i = 0; i < terminals.size(); i++) {
            if (terminals.get(i).getName().contains(requiredTerminal)) {
              usedCardTerminalName = terminals.get(i).getName();
              return;
            }
          }
        }
      }
    } catch (Throwable e) {
      // Probably no reader found...
      System.err.println("Unable to connect to RFID reader");
      e.printStackTrace();
    }
    return;
  }
Example #4
0
  /**
   * Function to connect to the MSC
   *
   * @throws TokenException
   */
  public void connect() throws TokenException {
    int i, j;

    try {
      /*
       * Get all available terminals..
       */
      TerminalFactory factory = TerminalFactory.getDefault();
      List<CardTerminal> terminals = factory.terminals().list();
      if (terminals.isEmpty()) {
        throw new TokenException("No terminals found");
      }

      /*
       * Select appropriate terminal
       */
      CardTerminal terminal = null;
      for (i = 0; i < terminals.size(); i++) {
        /*
         * Try the known terminal names the msc-driver uses..
         */
        for (j = 0; j < TERMINAL_NAMES.length; j++) {
          if (terminals.get(i).getName().startsWith(TERMINAL_NAMES[j])) {
            terminal = terminals.get(i);
            break;
          }
        }
      }
      if (terminal == null || !terminal.isCardPresent()) {
        throw new TokenException("No G&D MSC found in terminal(s)");
      }

      /*
       * Establish a connection with the myCard
       */
      myCard = terminal.connect("T=1");
      myChannel = myCard.getBasicChannel();

      /*
       * Of the several AIDs in distribution, try to select one that
       * actually works.. ;)
       */
      boolean appSelected = false;
      for (i = 0; i < APPLET_IDS.length; i++) {
        if (appSelected = selectApplet(APPLET_IDS[i])) {
          break;
        }
      }
      if (!appSelected) {
        throw new TokenException("Could not select Applet");
      }
    } catch (TokenException e) {
      throw e;
    } catch (Exception e) {
      throw new TokenException("Some exception occured: " + e.toString());
    }
  }
Example #5
0
  public static void main(String[] args) throws NoSuchProviderException, NoSuchAlgorithmException {
    System.out.println("Starting rfid-reader2keyboard");

    Security.insertProviderAt(new Smartcardio(), 1);
    TerminalFactory.getInstance("PC/SC", null);

    System.out.println("The following terminals were detected:");
    System.out.println(Read.listTerminals());

    System.out.println();
    System.out.println(
        "inventid RFID capturing is currently active. Close this dialog to deactivate.");
    System.out.println(
        "The most likely reason you see this is in order to resolve any issue you ay have found. Please follow"
            + " the instructions of inventid support and send these lines to the given email address");

    executorService.scheduleAtFixedRate(errorLogger, 10, 30, TimeUnit.SECONDS);
    executorService.scheduleAtFixedRate(detectorLoop, 10, 15, TimeUnit.SECONDS);

    Read reader = new Read();
    reader.startRunning();

    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                executorService.shutdownNow();
                System.out.println(
                    "inventid RFID capturing is now inactive. You can close this dialog");
              }
            });
  }
Example #6
0
 /**
  * Get the currently connected terminals
  *
  * @return the list of found terminals
  */
 public static List<CardTerminal> listTerminals() {
   // show the list of available terminals
   try {
     return TerminalFactory.getDefault().terminals().list();
   } catch (Throwable e) {
     return Lists.newArrayList();
   }
 }
Example #7
0
 /**
  * Used to get the name of the readers connected.
  *
  * @return A list of the names.
  */
 public ArrayList<String> getReadersName() {
   ArrayList<String> list = new ArrayList<>();
   try {
     for (CardTerminal terminal : terminalFactory.terminals().list()) list.add(terminal.getName());
   } catch (CardException exception) {
   }
   return list;
 }
Example #8
0
 /**
  * Constructor.
  *
  * @param name The name of the reader we should listen to.
  */
 public TerminalReader(String name) {
   this.listenersTerminal = new ArrayList<>();
   this.terminalName = name;
   this.logger = Logger.getGlobal();
   this.thread = new Thread(this);
   this.thread.setName("TerminalReader");
   this.thread.start();
   terminalFactory = TerminalFactory.getDefault();
 }
Example #9
0
  /**
   * Find and connect to a terminal, based on the preferences in TERMINAL_PREFERENCES
   *
   * @return a valid CardTerminal or halts the system if no match can be found
   */
  public void findAndConnectToTerminal() {
    try {
      synchronized (synchronizer) {
        // show the list of available terminals
        TerminalFactory factory = TerminalFactory.getDefault();
        List<CardTerminal> terminals = factory.terminals().list();

        for (int i = 0; i < terminals.size(); i++) {
          if (terminals.get(i).getName().equals(usedCardTerminalName)) {
            System.out.println("Attached to '" + usedCardTerminalName + "'");
            terminal = terminals.get(i);
            return;
          }
        }
      }
    } catch (Throwable e) {
      // Probably no reader found...
      System.err.println("Unable to connect to RFID reader");
      e.printStackTrace();
    }
    return;
  }
  public void run() {
    if (Log.logger != null) Log.logger.debug("Started CardReaderMonitorImpl thread");
    run = true;
    exit = false;
    boolean changed;
    boolean noReaders;
    terminals = factory.terminals();

    while (run) {
      synchronized (terms) {
        getStatusChange();
      }
      terminals = factory.terminals();
      changed = false;
      while (run && !changed) {
        noReaders = false;
        try {
          changed = terminals.waitForChange(LISTREADER_INTERVAL);
        } catch (Exception e) {
          noReaders = true;
        }
        if (run && noReaders) {
          synchronized (LISTREADER_INTERVAL) {
            try {
              LISTREADER_INTERVAL.wait(LISTREADER_INTERVAL);
            } catch (InterruptedException ie) {
              run = false;
            }
          }
        }
      }
    }
    synchronized (this) {
      exit = true;
      this.notify();
    }
    if (Log.logger != null) Log.logger.debug("Ending CardReaderMonitorImpl thread");
  }
  public void start() {

    TerminalFactory factory;
    try {
      factory = TerminalFactory.getInstance(TERMINAL_TYPE_PCSC, null);
    } catch (NoSuchAlgorithmException e1) {
      throw new RuntimeException(
          "Impossível estabelecer um  contexto; o serviço PCSC (pcscd) está executando?", e1);
    }
    this.terminals = factory.terminals();
    factory = null;

    try {
      this.terminals.list();
    } catch (CardException e) {
      throw new RuntimeException(e.getMessage(), e);
    }

    try {
      while (!this.interrompido) {
        this.terminals.waitForChange(WAIT_TIMEOUT_MS);
        if (this.terminals.list(CardTerminals.State.CARD_INSERTION).size() > 0) {
          LOGGER.fine("cartao detectado.");
          CardTerminal terminal = this.terminals.list(CardTerminals.State.CARD_INSERTION).get(0);
          this.currentCard = terminal.connect(PROTOCOL_ANY);
          this.notifyEvent(new CardEvent(this.currentCard, EventType.CARD_AVAILABLE));
        }
        if (this.terminals.list(CardTerminals.State.CARD_REMOVAL).size() > 0) {
          LOGGER.fine("cartao removido.");
          this.currentCard = null;
          this.notifyEvent(new CardEvent(this.currentCard, EventType.CARD_REMOVED));
        }
      }
    } catch (CardException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }
 /**
  * openChannel
  *
  * @param applet
  * @return Channel
  * @throws Exception
  */
 private CardChannel openChannel(AppletModel applet) throws Exception {
   if (channel != null) {
     try {
       channel.close();
     } catch (Exception e) {
       //
     }
     channel = null;
   }
   if (card != null) {
     try {
       card.disconnect(true);
     } catch (Exception e) {
       //
     }
     card = null;
   }
   TerminalFactory factory = TerminalFactory.getDefault();
   CardTerminals cardterminals = factory.terminals();
   try {
     List<CardTerminal> terminals = cardterminals.list();
     System.out.println("Terminals: " + terminals);
     for (CardTerminal terminal : terminals) {
       terminal.waitForCardPresent(1000);
       if (terminal.isCardPresent()) {
         System.out.println(terminal.getName() + ": Card present!");
         card = terminal.connect("*");
         channel = card.getBasicChannel();
         return channel;
       }
     }
     throw new WolfException(MSG_READER_TIME_OUT);
   } catch (Exception e) {
     throw e;
   }
 }
Example #13
0
 /**
  * What is doing the thread.
  *
  * <p>Will check if there is a reader available containing the wanted name (will call {@link
  * TerminalListener#cardReaderRemoved()} ()} if a listener is removed or added). If it is the case
  * it will wait for a card placed, call {@link TerminalListener#cardAdded(RFIDCard)}, wait for the
  * card to be removed then call {@link TerminalListener#cardRemoved()}
  */
 @Override
 public void run() {
   while (!Thread.interrupted()) {
     if (terminalFactory == null)
       try {
         Thread.sleep(500);
       } catch (InterruptedException e) {
       }
     boolean lastPresent = this.isPresent;
     try {
       final CardTerminals terminalList = terminalFactory.terminals();
       CardTerminal cardTerminal = null;
       try {
         for (CardTerminal terminal : terminalList.list())
           if (terminal.getName().equals(this.terminalName)) {
             cardTerminal = terminal;
             this.isPresent = true;
             break;
           }
       } catch (CardException exception) {
       }
       if (cardTerminal == null) this.isPresent = false;
       if (this.isPresent != lastPresent) {
         if (this.isPresent)
           logger.log(Level.INFO, "Starting listening terminal " + cardTerminal.getName());
         else logger.log(Level.INFO, "Stopped listening");
         for (TerminalListener listener : this.listenersTerminal)
           if (this.isPresent) listener.cardReaderAdded();
           else listener.cardReaderRemoved();
       }
       if (!this.isPresent) continue;
       logger.log(Level.INFO, "Waiting for card...");
       cardTerminal.waitForCardPresent(0);
       logger.log(Level.INFO, "Card detected");
       this.lastCard = getCardInfos(cardTerminal.connect("*"));
       for (TerminalListener listener : this.listenersTerminal) listener.cardAdded(this.lastCard);
       cardTerminal.waitForCardAbsent(0);
       this.lastCard = null;
       logger.log(Level.INFO, "Card removed");
       for (TerminalListener listener : this.listenersTerminal) listener.cardRemoved();
     } catch (Exception exception) {
       logger.log(Level.WARNING, "", exception);
     }
   }
 }
Example #14
0
  public static void main(String[] argv) throws Exception {
    OptionSet args = parseOptions(argv);

    if (args.has(OPT_VERBOSE)) {
      verbose = true;
      // Set up slf4j simple in a way that pleases us
      System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug");
      System.setProperty("org.slf4j.simpleLogger.showThreadName", "true");
      System.setProperty("org.slf4j.simpleLogger.showShortLogName", "true");
      System.setProperty("org.slf4j.simpleLogger.levelInBrackets", "true");
    } else {
      System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "warn");
    }

    if (args.has(OPT_VERSION)) {
      String version = "apdu4j " + getVersion(SCTool.class);
      // Append host information
      version += "\nRunning on " + System.getProperty("os.name");
      version += " " + System.getProperty("os.version");
      version += " " + System.getProperty("os.arch");
      version += ", Java " + System.getProperty("java.version");
      version += " by " + System.getProperty("java.vendor");
      System.out.println(version);
    }
    if (args.has(OPT_TEST_SERVER)) {
      // TODO: have the possibility to run SocketServer as well?
      RemoteTerminalServer srv = new RemoteTerminalServer(TestServer.class);
      srv.start(string2socket((String) args.valueOf(OPT_TEST_SERVER)));
      System.console().readLine("Press enter to stop\n");
      srv.stop(1);
      System.exit(0);
    }

    // List TerminalFactory providers
    if (args.has(OPT_PROVIDERS)) {
      Provider providers[] = Security.getProviders("TerminalFactory.PC/SC");
      if (providers != null) {
        System.out.println("Existing TerminalFactory providers:");
        for (Provider p : providers) {
          System.out.println(p.getName());
        }
      }
    }

    // Fix properties on non-windows platforms
    TerminalManager.fixPlatformPaths();

    // Only applies to SunPCSC
    if (args.has(OPT_NO_GET_RESPONSE)) {
      System.setProperty("sun.security.smartcardio.t0GetResponse", "false");
      System.setProperty("sun.security.smartcardio.t1GetResponse", "false");
    }

    // Override PC/SC library path
    if (args.has(OPT_LIB)) {
      System.setProperty("sun.security.smartcardio.library", (String) args.valueOf(OPT_LIB));
    }

    TerminalFactory tf = null;
    CardTerminals terminals = null;

    try {
      // Get a terminal factory
      if (args.has(OPT_PROVIDER)) {
        String pn = (String) args.valueOf(OPT_PROVIDER);
        String pt = (String) args.valueOf(OPT_PROVIDER_TYPE);
        tf = loadFactory(pn, pt);
      } else if (args.has(OPT_SUN)) {
        tf = loadFactory(SUN_CLASS, null);
      } else if (args.has(OPT_JNA)) {
        tf = loadFactory(JNA_CLASS, null);
      } else {
        tf = TerminalFactory.getDefault();
      }

      if (verbose) {
        System.out.println(
            "# Using " + tf.getProvider().getClass().getCanonicalName() + " - " + tf.getProvider());
        if (System.getProperty(TerminalManager.lib_prop) != null) {
          System.out.println(
              "# " + TerminalManager.lib_prop + "=" + System.getProperty(TerminalManager.lib_prop));
        }
      }
      // Get all terminals
      terminals = tf.terminals();
    } catch (Exception e) {
      // XXX: we catch generic Exception here to avoid importing JNA.
      // Try to get a meaningful message
      String msg = TerminalManager.getExceptionMessage(e);
      if (msg == null) msg = e.getMessage();
      System.out.println("No readers: " + msg);
      System.exit(1);
    }

    // Terminals to work on
    List<CardTerminal> do_readers = new ArrayList<CardTerminal>();

    try {
      // List Terminals
      if (args.has(CMD_LIST)) {
        List<CardTerminal> terms = terminals.list();
        if (verbose) {
          System.out.println(
              "# Found " + terms.size() + " terminal" + (terms.size() == 1 ? "" : "s"));
        }
        if (terms.size() == 0) {
          System.err.println("No readers found");
          System.exit(1);
        }
        for (CardTerminal t : terms) {
          String vmd = " ";
          try (PinPadTerminal pp = new PinPadTerminal(t)) {
            pp.probe();
            // Verify, Modify, Display
            if (verbose) {
              vmd += "[";
              vmd += pp.canVerify() ? "V" : " ";
              vmd += pp.canModify() ? "M" : " ";
              vmd += pp.hasDisplay() ? "D" : " ";
              vmd += "] ";
            }
          } catch (CardException e) {
            if (verbose) {
              System.err.println("Could not probe PinPad: " + e.getMessage());
            }
          }

          System.out.println((t.isCardPresent() ? "[*]" : "[ ]") + vmd + t.getName());

          if (args.has(OPT_VERBOSE) && t.isCardPresent()) {
            Card c = t.connect("DIRECT");
            String atr = HexUtils.encodeHexString(c.getATR().getBytes()).toUpperCase();
            c.disconnect(false);
            System.out.println("          " + atr);
            if (args.has(OPT_WEB)) {
              String url = "http://smartcard-atr.appspot.com/parse?ATR=" + atr;
              if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(url + "&from=apdu4j"));
              } else {
                System.out.println("          " + url);
              }
            }
          }
        }
      }

      // Select terminals to work on
      if (args.has(OPT_READER)) {
        String reader = (String) args.valueOf(OPT_READER);
        CardTerminal t = terminals.getTerminal(reader);
        if (t == null) {
          System.err.println("Reader \"" + reader + "\" not found.");
          System.exit(1);
        }
        do_readers = Arrays.asList(t);
      } else {
        do_readers = terminals.list(State.CARD_PRESENT);
        if (do_readers.size() > 1 && !args.hasArgument(OPT_ALL)) {
          System.err.println("More than one reader with a card found.");
          System.err.println("Run with --" + OPT_ALL + " to work with all found cards");
          System.exit(1);
        } else if (do_readers.size() == 0 && !args.has(CMD_LIST)) {
          // But if there is a single reader, wait for a card insertion
          List<CardTerminal> empty = terminals.list(State.CARD_ABSENT);
          if (empty.size() == 1 && args.has(OPT_WAIT)) {
            CardTerminal rdr = empty.get(0);
            System.out.println("Please enter a card into " + rdr.getName());
            if (!empty.get(0).waitForCardPresent(30000)) {
              System.out.println("Timeout.");
            } else {
              do_readers = Arrays.asList(rdr);
            }
          } else {
            System.err.println("No reader with a card found!");
            System.exit(1);
          }
        }
      }

    } catch (CardException e) {
      System.out.println("Could not list readers: " + TerminalManager.getExceptionMessage(e));
      e.printStackTrace();
    }

    for (CardTerminal t : do_readers) {
      work(t, args);
    }
  }
 public void start() {
   factory = TerminalFactory.getDefault();
   terms = new ArrayList<CardTerminal>();
   termsCardPresent = new ArrayList<Boolean>();
   new Thread(this).start();
 }