Java Code Examples for javax.smartcardio.ResponseAPDU#getSW()

The following examples show how to use javax.smartcardio.ResponseAPDU#getSW() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void verifyPin(char[] pin) throws TechnicalConnectorException {
   try {
      ResponseAPDU responseApdu = verifyPIN(pin);
      if (36864 != responseApdu.getSW()) {
         LOG.debug("VERIFY_PIN error");
         LOG.debug("SW: " + Integer.toHexString(responseApdu.getSW()));
         if (27011 == responseApdu.getSW()) {
            throw new BeIDPinCodeException(new ResponseAPDUException("eID card blocked!", responseApdu));
         } else if (99 != responseApdu.getSW1()) {
            LOG.debug("PIN verification error.");
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         } else {
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         }
      }
   } catch (CardNotPresentException var2) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_EID_NULL, var2, new Object[0]);
   } catch (CardException var3) {
      throw new BeIDPinCodeException(var3);
   }
}
 
Example 2
Source File: JCMathLibTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void testAPDU(CardManager cardMngr, String input, String expectedOutput) {
    try {
        ResponseAPDU response = cardMngr.transmit(new CommandAPDU(hexStringToByteArray(input)));
        if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {
            if (!expectedOutput.isEmpty()) {
                byte[] data = response.getData();
                String output = Util.bytesToHex(data);
                assertTrue(expectedOutput.equalsIgnoreCase(output), "Result provided by card mismatch expected");
            }
        }
        else {
            assertTrue(false, String.format("Card failed with 0x%x", response.getSW()));
        }                
    }
    catch (Exception e) {
        e.printStackTrace();
        assertTrue(false, "Card transmit failed with execption");
    }
}
 
Example 3
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void verifyPin(char[] pin) throws TechnicalConnectorException {
   try {
      ResponseAPDU responseApdu = verifyPIN(pin);
      if (36864 != responseApdu.getSW()) {
         LOG.debug("VERIFY_PIN error");
         LOG.debug("SW: " + Integer.toHexString(responseApdu.getSW()));
         if (27011 == responseApdu.getSW()) {
            throw new BeIDPinCodeException(new ResponseAPDUException("eID card blocked!", responseApdu));
         } else if (99 != responseApdu.getSW1()) {
            LOG.debug("PIN verification error.");
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         } else {
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         }
      }
   } catch (CardNotPresentException var2) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_EID_NULL, var2, new Object[0]);
   } catch (CardException var3) {
      throw new BeIDPinCodeException(var3);
   }
}
 
Example 4
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void verifyPin(char[] pin) throws TechnicalConnectorException {
   try {
      ResponseAPDU responseApdu = verifyPIN(pin);
      if (36864 != responseApdu.getSW()) {
         LOG.debug("VERIFY_PIN error");
         LOG.debug("SW: " + Integer.toHexString(responseApdu.getSW()));
         if (27011 == responseApdu.getSW()) {
            throw new BeIDPinCodeException(new ResponseAPDUException("eID card blocked!", responseApdu));
         } else if (99 != responseApdu.getSW1()) {
            LOG.debug("PIN verification error.");
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         } else {
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         }
      }
   } catch (CardNotPresentException var2) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_EID_NULL, var2, new Object[0]);
   } catch (CardException var3) {
      throw new BeIDPinCodeException(var3);
   }
}
 
Example 5
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void verifyPin(char[] pin) throws TechnicalConnectorException {
   try {
      ResponseAPDU responseApdu = verifyPIN(pin);
      if (36864 != responseApdu.getSW()) {
         LOG.debug("VERIFY_PIN error");
         LOG.debug("SW: " + Integer.toHexString(responseApdu.getSW()));
         if (27011 == responseApdu.getSW()) {
            throw new BeIDPinCodeException(new ResponseAPDUException("eID card blocked!", responseApdu));
         } else if (99 != responseApdu.getSW1()) {
            LOG.debug("PIN verification error.");
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         } else {
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         }
      }
   } catch (CardNotPresentException var2) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_EID_NULL, var2, new Object[0]);
   } catch (CardException var3) {
      throw new BeIDPinCodeException(var3);
   }
}
 
Example 6
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void verifyPin(char[] pin) throws TechnicalConnectorException {
   try {
      ResponseAPDU responseApdu = verifyPIN(pin);
      if (36864 != responseApdu.getSW()) {
         LOG.debug("VERIFY_PIN error");
         LOG.debug("SW: " + Integer.toHexString(responseApdu.getSW()));
         if (27011 == responseApdu.getSW()) {
            throw new BeIDPinCodeException(new ResponseAPDUException("eID card blocked!", responseApdu));
         } else if (99 != responseApdu.getSW1()) {
            LOG.debug("PIN verification error.");
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         } else {
            throw new BeIDPinCodeException(new ResponseAPDUException("PIN Verification Error", responseApdu));
         }
      }
   } catch (CardNotPresentException var2) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_EID_NULL, var2, new Object[0]);
   } catch (CardException var3) {
      throw new BeIDPinCodeException(var3);
   }
}
 
Example 7
Source File: GpgCryptoTest.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Receive more than 256 bytes from the card using command chaining.
 */
private byte[] receiveLong(ResponseAPDU r) throws CardException {
  byte[] data = new byte[0];
  for (; ; ) {
    data = mergeByteArrays(data, r.getData());
    if (r.getSW() == 0x9000) {
      break;
    }
    assertEquals(0x61, r.getSW1());
    r = card.sendAPDU(0, 0xC0, 0, 0, r.getSW2());
  }
  return data;
}
 
Example 8
Source File: GenericAPDU.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void sendArg(PrintStream os, GenericCard card, CardChannel channel, byte[] data) throws CardException {
    CommandAPDU capdu = APDUUtil.buildCommand(
            apduCLA, apduINS, apduP12, data
    );
    os.println("APDU > " + APDUUtil.toString(capdu));
    ResponseAPDU rapdu = card.transmit(channel, capdu);
    os.println("APDU < " + APDUUtil.toString(rapdu));
    int sw = rapdu.getSW();
    if (sw != ISO7816.SW_NO_ERROR) {
        throw new SWException("Error executing command", sw);
    }
}
 
Example 9
Source File: GenericAPDU.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void sendRaw(PrintStream os, GenericCard card, CardChannel channel) throws CardException {
    for(byte[] apdu: raw) {
        CommandAPDU capdu = new CommandAPDU(apdu);
        os.println("APDU > " + APDUUtil.toString(capdu));
        ResponseAPDU rapdu = card.transmit(channel, capdu);
        os.println("APDU < " + APDUUtil.toString(rapdu));
        int sw = rapdu.getSW();
        if(sw != ISO7816.SW_NO_ERROR) {
            throw new SWException("Error executing command", sw);
        }
    }
}
 
Example 10
Source File: NdefClient.java    From openjavacard-ndef with GNU General Public License v3.0 5 votes vote down vote up
private ResponseAPDU transactAndCheck(CommandAPDU capdu) throws CardException {
    ResponseAPDU rapdu = mChannel.transmit(capdu);
    int sw = rapdu.getSW();
    if(sw != 0x9000) {
        throw new CardException("Card returned error " + sw);
    }
    return rapdu;
}
 
Example 11
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseAPDU execute(String Command, int expectedReturn) {
    ResponseAPDU response = execute(Command,display);
    if(response.getSW() != expectedReturn) {
        fail("expected: " + Integer.toHexString(expectedReturn) + " but was: " + Integer.toHexString(response.getSW()));
    }
    return response;
}
 
Example 12
Source File: GPSecureChannel.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Internal transmit method
 * <p/>
 * This variant does not check if the channel is fully established.
 * This is used during secure channel setup.
 * <p/>
 * @param command be wrapped and sent
 * @return the unwrapped response
 * @throws CardException
 */
private ResponseAPDU transmitInternal(CommandAPDU command) throws CardException {
    boolean traceEnabled = LOG.isTraceEnabled();
    // bug out if the channel is not open
    if (mWrapper == null) {
        throw new CardException("Secure channel is not connected");
    }
    // wrap the command (sign, encrypt)
    CommandAPDU wrappedCommand = mWrapper.wrap(command);
    // send the wrapped command
    ResponseAPDU wrappedResponse = mBasicWrapper.transmitRaw(wrappedCommand);
    // unwrap the response, but not if it is an error
    int sw = wrappedResponse.getSW();
    ResponseAPDU response = wrappedResponse;
    if (sw == ISO7816.SW_NO_ERROR || SW.isWarning(sw)) {
        // unwrap the response (decrypt, verify)
        response = mWrapper.unwrap(wrappedResponse);
    } else {
        // data in error responses is illegal
        int dataLen = response.getNr();
        if (dataLen > 0) {
            throw new CardException("Card sent data in an error response");
        }
    }
    // return unwrapped response
    return response;
}
 
Example 13
Source File: GPSecureChannel.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Strictly check a response (and throw if it is an error)
 * <p/>
 * @param response to check
 * @throws CardException if the response is an error
 */
private void checkResponse(ResponseAPDU response) throws CardException {
    int sw = response.getSW();
    if (sw != ISO7816.SW_NO_ERROR) {
        throw new SWException("Error in secure channel authentication", sw);
    }
}
 
Example 14
Source File: TestClient.java    From JCMathLib with MIT License 5 votes vote down vote up
public boolean compare(ResponseAPDU response) {
    boolean bResult = false;
    if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {
        bResult = Arrays.equals(m_expected.getEncoded(), response.getData());
    } else {
        bResult = false;
        System.out.println(String.format("fail (0x%x)", response.getSW()));
    }
    return bResult;
}
 
Example 15
Source File: TestClient.java    From JCMathLib with MIT License 5 votes vote down vote up
static boolean verifyAndLogResponse(String operationName, ResponseAPDU response, Long lastTransmitTime, int expected, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {
    boolean bResult = false;
    if (response.getSW () == (ISO7816.SW_NO_ERROR & 0xffff)) {
        bResult = Util.BytesToInt(response.getData()) == expected;
    }
    else {
        System.out.println(String.format("fail (0x%x)", response.getSW()));
    }
    logResponse(operationName, bResult, lastTransmitTime, perfFile, failedTestsList);
    return bResult;
}
 
Example 16
Source File: PhysicalCard.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean selectApplet(byte[] aid) throws CardException {
  CommandAPDU select = new CommandAPDU(0, 0xa4, 4, 0, aid);
  logger.info(formatCommandAPDU(select));
  ResponseAPDU r = channel.transmit(select);
  logger.info(r.getSW() == 0x9000 ? "[OK]" : String.format("[%04X]", r.getSW()) +
                                             " Applet selection: " + bytesToHex(aid));
  return r.getSW() == 0x9000;
}
 
Example 17
Source File: Util.java    From JCMathLib with MIT License 5 votes vote down vote up
private static boolean checkSW(ResponseAPDU response) {
    if (response.getSW() != (ISO7816.SW_NO_ERROR & 0xffff)) {
        System.err.printf("Received error status: %02X.\n",
                response.getSW());
        return false;
    }
    return true;
}
 
Example 18
Source File: CardManager.java    From JCMathLib with MIT License 4 votes vote down vote up
private CardChannel connectToCardByTerminalFactory(TerminalFactory factory, int targetReaderIndex) throws CardException {
    List<CardTerminal> terminals = new ArrayList<>();

    boolean card_found = false;
    CardTerminal terminal = null;
    Card card = null;
    try {
        for (CardTerminal t : factory.terminals().list()) {
            terminals.add(t);
            if (t.isCardPresent()) {
                card_found = true;
            }
        }
    } catch (Exception ignored) {
    }

    if (card_found) {
        System.out.println("Cards found: " + terminals);

        terminal = terminals.get(targetReaderIndex); 

        System.out.print("Connecting...");
        card = terminal.connect("*"); 

        System.out.println(" done.");

        System.out.print("Establishing channel...");
        m_channel = card.getBasicChannel();

        System.out.println(" done.");

        System.out.print("Selecting applet...");

        CommandAPDU cmd = new CommandAPDU(0x00, 0xa4, 0x04, 0x00, m_APPLET_AID);
        ResponseAPDU response = transmit(cmd);
        if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {
            System.out.print(" done");
        }
        else {
            System.out.print(" failed.");
        }
        
    } else {
        System.out.print("Failed to find required card.");
    }

    if (card != null) {
        return card.getBasicChannel();
    } else {
        return null;
    }
}
 
Example 19
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Perform a GlobalPlatform SET STATUS operation
 *
 * @param p1Subset
 * @param p2Format
 * @param criteria
 * @return data retrieved
 * @throws CardException on error
 */
private ArrayList<byte[]> performReadStatus(byte p1Subset, byte p2Format, byte[] criteria) throws CardException {
    LOG.trace("performReadStatus()");
    ArrayList<byte[]> res = new ArrayList<>();
    boolean first = true;
    do {
        // determine first/next parameter
        byte getParam = GP.GET_STATUS_P2_GET_NEXT;
        if (first) {
            getParam = GP.GET_STATUS_P2_GET_FIRST_OR_ALL;
        }
        first = false;
        // build the command
        CommandAPDU command = APDUUtil.buildCommand(
                GP.CLA_GP,
                GP.INS_GET_STATUS,
                p1Subset, (byte) (getParam | p2Format), criteria);
        // run the command
        ResponseAPDU response = transactSecure(command);
        // get SW and data
        int sw = response.getSW();
        byte[] data = response.getData();
        // append data, no matter the SW
        if (data != null && data.length > 0) {
            res.add(data);
        }
        // continue if SW says that we should
        //   XXX extract this constant
        if (sw == 0x6310) {
            continue;
        }
        // check for various cases of "empty"
        //   XXX rethink this loop
        if (sw == ISO7816.SW_NO_ERROR
                || sw == ISO7816.SW_FILE_NOT_FOUND
                || sw == ISO7816.SW_REFERENCED_DATA_NOT_FOUND) {
            break;
        } else {
            throw new SWException("Error in GET STATUS", sw);
        }
    } while (true);
    return res;
}
 
Example 20
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 4 votes vote down vote up
protected void authenticateMutual(byte[] key, boolean successexpected) {
    byte[] myChallenge= new byte [16], globalchallenge = new byte[40], challengeresponse = new byte[40];
    byte[] cardChallenge;
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);
    new Random().nextBytes(myChallenge);
    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 14 7C 12 81 10" + DatatypeConverter.printHexBinary(myChallenge) + "00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x12,(byte) 0x81,0x10})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    cardChallenge = Arrays.copyOfRange(response.getBytes(), 4, 20);
    //solve challenge
    //R2
    System.arraycopy(cardChallenge, 0, globalchallenge, 0, 16);
    //R1
    System.arraycopy(myChallenge, 0, globalchallenge, 16, 16);
    // keep Z1 random
    globalchallenge[(short)39] = (byte) 0x80;
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(globalchallenge, (short) 0, (short)40, challengeresponse, (short) 0);
    // send the response
    String command = "00 87 00 00 2C 7C 2A 82 28" + DatatypeConverter.printHexBinary(challengeresponse);
    
    ResponseAPDU responseAPDU = execute(command, true);
    
    if (!successexpected)
    {
        if(responseAPDU.getSW() != 0x6982) {
            fail("expected: " + Integer.toHexString(0x6982) + " but was: " + Integer.toHexString(response.getSW()));
        }
        return;
    }
    if(responseAPDU.getSW() != 0x9000) {
        fail("expected: " + Integer.toHexString(0x9000) + " but was: " + Integer.toHexString(response.getSW()));
    }
    byte[] cardresponse = responseAPDU.getBytes();
    if (!Arrays.equals(Arrays.copyOfRange(cardresponse, 0, 4), new byte[] {0x7C,0x2A,(byte)0x82,0x28}))
    {
        fail("header verification failed");
    }
    byte[] decryptedCardResponse = new byte[40];
    cipherDES.init(deskey, Cipher.MODE_DECRYPT);
    cipherDES.doFinal(cardresponse, (short) 4, (short)40, decryptedCardResponse, (short) 0);
   
    
    if (!Arrays.equals(Arrays.copyOfRange(decryptedCardResponse, 0, 16), myChallenge)) {
        fail("R1 verification failed");
    }
    
    if (!Arrays.equals(Arrays.copyOfRange(decryptedCardResponse, 16, 32), cardChallenge)) {
        fail("R2 verification failed");
    }
    if (decryptedCardResponse[(short)39] != (byte) 0x80) {
        fail("padding failed");
    }
    
}