javax.smartcardio.CardException Java Examples

The following examples show how to use javax.smartcardio.CardException. 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: GPSecureChannel.java    From openjavacard-tools with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * Assemble and transact an INITIALIZE UPDATE command
 * <p/>
 * The command will be sent on the underlying unencrypted channel.
 * <p/>
 * @param keyVersion    to indicate
 * @param keyId         to indicate
 * @param hostChallenge to send
 * @return a decoded response to the command
 * @throws CardException on error
 */
private GPInitUpdateResponse performInitializeUpdate(byte keyVersion, byte keyId, byte[] hostChallenge) throws CardException {
    LOG.trace("performInitializeUpdate()");
    // build the command
    CommandAPDU initCommand = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_INITIALIZE_UPDATE,
            keyVersion,
            keyId,
            hostChallenge
    );
    // and transmit it on the underlying channel
    ResponseAPDU initResponse = mBasicWrapper.transmitRaw(initCommand);
    // check the response
    checkResponse(initResponse);
    // parse the response
    byte[] responseData = initResponse.getData();
    GPInitUpdateResponse response = new GPInitUpdateResponse(responseData);
    // return the parsed response
    return response;
}
 
Example #2
Source File: GPCommand.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Executed before performing the operation
 * @param card
 * @throws CardException
 */
private void beforeOperation(GPCard card) throws CardException {
    PrintStream os = System.out;

    AID isdConf = card.getISD();
    os.println("Host GP configuration:");
    os.println("  ISD " + ((isdConf==null)?"auto":isdConf));
    int protocol = HexUtil.unsigned8(scpProtocol);
    int parameters = HexUtil.unsigned8(scpParameters);
    SCPProtocolPolicy protocolPolicy = new SCPProtocolPolicy(protocol, parameters);
    os.println("  Key diversification " + scpDiversification);
    card.setDiversification(scpDiversification);
    os.println("  Protocol policy " + protocolPolicy);
    card.setProtocolPolicy(protocolPolicy);
    os.println("  Security policy " + scpSecurity);
    card.setSecurityPolicy(scpSecurity);
    os.println();
    os.println("CONNECTING");
    card.connect();
    os.println();
}
 
Example #3
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
public GPInstallForLoadResponse performInstallForLoad(GPInstallForLoadRequest request) throws CardException {
    LOG.trace("performInstallForLoad()");
    // serialize the request
    byte[] requestBytes = request.toBytes();
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_INSTALL,
            GP.INSTALL_P1_FOR_LOAD,
            GP.INSTALL_P2_NO_INFORMATION,
            requestBytes);
    // perform the operation
    ResponseAPDU responseAPDU = transactSecureAndCheck(command);
    // parse and return response
    GPInstallForLoadResponse response = new GPInstallForLoadResponse();
    response.readBytes(responseAPDU.getData());
    return response;
}
 
Example #4
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized void endExclusive() throws CardException {
   this.checkState();
   if (this.exclusiveThread != Thread.currentThread()) {
      throw new IllegalStateException("Exclusive access not assigned to current Thread");
   } else {
      try {
         PCSC.SCardEndTransaction(this.cardId, 0);
      } catch (PCSCException var5) {
         this.handleError(var5);
         throw new CardException("beginExclusive() failed", var5);
      } finally {
         this.exclusiveThread = null;
      }

   }
}
 
Example #5
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized void beginExclusive() throws CardException {
   this.checkSecurity("exclusive");
   this.checkState();
   if (this.exclusiveThread != null) {
      throw new CardException("Exclusive access has already been assigned to Thread " + this.exclusiveThread.getName());
   } else {
      try {
         PCSC.SCardBeginTransaction(this.cardId);
      } catch (PCSCException var2) {
         this.handleError(var2);
         throw new CardException("beginExclusive() failed", var2);
      }

      this.exclusiveThread = Thread.currentThread();
   }
}
 
Example #6
Source File: TerminalImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized Card connect(String protocol) throws CardException {
   if (this.card != null) {
      if (this.card.isValid()) {
         String cardProto = this.card.getProtocol();
         if (!protocol.equals("*") && !protocol.equalsIgnoreCase(cardProto)) {
            throw new CardException("Cannot connect using " + protocol + ", connection already established using " + cardProto);
         }

         return this.card;
      }

      this.card = null;
   }

   try {
      this.card = new CardImpl(this, protocol);
      return this.card;
   } catch (PCSCException var3) {
      if (var3.code == -2146434967) {
         throw new CardNotPresentException("No card present", var3);
      } else {
         throw new CardException("connect() failed", var3);
      }
   }
}
 
Example #7
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] transmitControlCommand(int controlCode, byte[] command) throws CardException {
   this.checkSecurity("transmitControl");
   this.checkState();
   this.checkExclusive();
   if (command == null) {
      throw new NullPointerException();
   } else {
      try {
         byte[] r = PCSC.SCardControl(this.cardId, controlCode, command);
         return r;
      } catch (PCSCException var4) {
         this.handleError(var4);
         throw new CardException("transmitControlCommand() failed : " + var4.getMessage(), var4);
      }
   }
}
 
Example #8
Source File: ScanFID.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ResponseAPDU performSelect(GenericCard card, int fid, boolean first) throws CardException {
    byte p1;
    if(customP1 < 0) {
        p1 = ISO7816.SELECT_P1_BY_FILEID;
    } else {
        p1 = (byte)customP1;
    }
    byte p2;
    if(customP2 < 0) {
        p2 = first ? ISO7816.SELECT_P2_FIRST_OR_ONLY : ISO7816.SELECT_P2_NEXT;
    } else {
        p2 = (byte)customP2;
    }
    byte[] fidBytes = new byte[2];
    BinUtil.setShort(fidBytes, 0, (short)fid);
    CommandAPDU scapdu = APDUUtil.buildCommand(
            ISO7816.CLA_ISO7816, ISO7816.INS_SELECT,
            p1, p2, fidBytes);
    return card.transmit(scapdu);
}
 
Example #9
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized void endExclusive() throws CardException {
   this.checkState();
   if (this.exclusiveThread != Thread.currentThread()) {
      throw new IllegalStateException("Exclusive access not assigned to current Thread");
   } else {
      try {
         PCSC.SCardEndTransaction(this.cardId, 0);
      } catch (PCSCException var5) {
         this.handleError(var5);
         throw new CardException("beginExclusive() failed", var5);
      } finally {
         this.exclusiveThread = null;
      }

   }
}
 
Example #10
Source File: GPBasicWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Read the cards Card Image Number (CIN)
 *
 * @return the CIN
 * @throws CardException on error
 */
public byte[] readCardCIN() throws CardException {
    LOG.trace("readCardCIN()");
    byte[] data = readData(GP.GET_DATA_P12_CARD_IMG_NUMBER);
    if(data == null) {
        return null;
    } else {
        try {
            return TLVPrimitive.readPrimitive(data)
                    .asPrimitive(TAG_CARD_IMG_NUMBER)
                    .getValueBytes();
        } catch (TLVException e) {
            throw new CardException("Error parsing CIN TLV", e);
        }
    }
}
 
Example #11
Source File: ChannelImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void close() throws CardException {
   if (this.getChannelNumber() == 0) {
      throw new IllegalStateException("Cannot close basic logical channel");
   } else if (!this.isClosed) {
      this.card.checkExclusive();

      try {
         byte[] com = new byte[]{0, 112, -128, (byte)this.getChannelNumber()};
         this.setChannel(com);
         byte[] res = PCSC.SCardTransmit(this.card.cardId, this.card.protocol, com, 0, com.length);
         if (!isOK(res)) {
            throw new CardException("close() failed: " + PCSC.toString(res));
         }
      } catch (PCSCException var6) {
         this.card.handleError(var6);
         throw new CardException("Could not close channel", var6);
      } finally {
         this.isClosed = true;
      }

   }
}
 
Example #12
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void performPutKey(int keyId, int keyVersion, byte[] keyData, boolean multipleKeys) throws CardException {
    LOG.trace("performPutKey()");
    // we only support atomic PUT KEY for now
    boolean moreCommands = false;
    // build parameters
    byte p1 = (byte)((keyVersion & 0x7F) | (moreCommands?0x80:0x00));
    byte p2 = (byte)((keyId & 0x7F) | (multipleKeys?0x80:0x00));
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_PUT_KEY,
            p1, p2,
            keyData
    );
    // execute it
    transactSecureAndCheck(command);
}
 
Example #13
Source File: GPRegistry.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Perform GET STATUS using TLV format
 *
 * @param p1Subset subset parameter
 * @param clazz to instantiate
 * @param <E> class of entry
 * @return list of entries
 * @throws CardException on error
 */
private <E extends Entry>
List<E> readStatusTLV(byte p1Subset, Class<E> clazz) throws CardException, TLVException {
    byte format = GP.GET_STATUS_P2_FORMAT_TLV;
    List<byte[]> chunks = mWrapper.performReadStatus(p1Subset, format);
    List<E> res = new ArrayList<>();
    for (byte[] chunk : chunks) {
        List<TLVPrimitive> tlvs = TLVPrimitive.readPrimitives(chunk);
        for (TLVPrimitive tlv : tlvs) {
            try {
                E entry = clazz.newInstance();
                entry.readTLV(tlv.getValueBytes());
                res.add(entry);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new Error("Error instantiating registry entry", e);
            }
        }
    }
    return res;
}
 
Example #14
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized void endExclusive() throws CardException {
   this.checkState();
   if (this.exclusiveThread != Thread.currentThread()) {
      throw new IllegalStateException("Exclusive access not assigned to current Thread");
   } else {
      try {
         PCSC.SCardEndTransaction(this.cardId, 0);
      } catch (PCSCException var5) {
         this.handleError(var5);
         throw new CardException("beginExclusive() failed", var5);
      } finally {
         this.exclusiveThread = null;
      }

   }
}
 
Example #15
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] transmitControlCommand(int controlCode, byte[] command) throws CardException {
   this.checkSecurity("transmitControl");
   this.checkState();
   this.checkExclusive();
   if (command == null) {
      throw new NullPointerException();
   } else {
      try {
         byte[] r = PCSC.SCardControl(this.cardId, controlCode, command);
         return r;
      } catch (PCSCException var4) {
         this.handleError(var4);
         throw new CardException("transmitControlCommand() failed : " + var4.getMessage(), var4);
      }
   }
}
 
Example #16
Source File: ChannelImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public int transmit(ByteBuffer command, ByteBuffer response) throws CardException {
   this.checkClosed();
   this.card.checkExclusive();
   if (command != null && response != null) {
      if (response.isReadOnly()) {
         throw new ReadOnlyBufferException();
      } else if (command == response) {
         throw new IllegalArgumentException("command and response must not be the same object");
      } else if (response.remaining() < 258) {
         throw new IllegalArgumentException("Insufficient space in response buffer");
      } else {
         byte[] commandBytes = new byte[command.remaining()];
         command.get(commandBytes);
         byte[] responseBytes = this.doTransmit(commandBytes);
         response.put(responseBytes);
         return responseBytes.length;
      }
   } else {
      throw new NullPointerException();
   }
}
 
Example #17
Source File: TerminalImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public synchronized Card connect(String protocol) throws CardException {
   if (this.card != null) {
      if (this.card.isValid()) {
         String cardProto = this.card.getProtocol();
         if (!protocol.equals("*") && !protocol.equalsIgnoreCase(cardProto)) {
            throw new CardException("Cannot connect using " + protocol + ", connection already established using " + cardProto);
         }

         return this.card;
      }

      this.card = null;
   }

   try {
      this.card = new CardImpl(this, protocol);
      return this.card;
   } catch (PCSCException var3) {
      if (var3.code == -2146434967) {
         throw new CardNotPresentException("No card present", var3);
      } else {
         throw new CardException("connect() failed", var3);
      }
   }
}
 
Example #18
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 #19
Source File: CardImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void disconnect(boolean reset) throws CardException {
   if (reset) {
      this.checkSecurity("reset");
   }

   if (this.state == CardImpl.State.OK) {
      this.checkExclusive();

      try {
         PCSC.SCardDisconnect(this.cardId, reset ? 0 : 1);
      } catch (PCSCException var6) {
         throw new CardException("disconnect() failed", var6);
      } finally {
         this.state = CardImpl.State.DISCONNECTED;
         this.exclusiveThread = null;
      }

   }
}
 
Example #20
Source File: SCPSecurityPolicyTest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCMACAccept() throws CardException {
    SCPSecurityPolicy pol = SCPSecurityPolicy.CMAC;
    pol.checkProtocol(SCP01_05);
    pol.checkProtocol(SCP01_15);
    pol.checkProtocol(SCP02_15);
    pol.checkProtocol(SCP02_55);
    pol.checkProtocol(SCP03_30);
    pol.checkProtocol(SCP03_70);
}
 
Example #21
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 #22
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 #23
Source File: ChannelImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public ResponseAPDU transmit(CommandAPDU command) throws CardException {
   this.checkClosed();
   this.card.checkExclusive();
   byte[] commandBytes = command.getBytes();
   byte[] responseBytes = this.doTransmit(commandBytes);
   return new ResponseAPDU(responseBytes);
}
 
Example #24
Source File: SCPProtocolPolicyTest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSCP01Accept() throws CardException {
    SCPProtocolPolicy pol = SCPProtocolPolicy.SCP01;
    Assert.assertTrue(pol.isVersionAllowed(0x01));
    Assert.assertFalse(pol.isVersionAllowed(0x02));
    Assert.assertFalse(pol.isVersionAllowed(0x03));
    Assert.assertFalse(pol.isProtocolAllowed(0x02, 0x15));
    Assert.assertFalse(pol.isProtocolAllowed(0x02, 0x55));
    Assert.assertTrue(pol.isProtocolAllowed(SCP01_05));
    Assert.assertTrue(pol.isProtocolAllowed(SCP01_15));
    Assert.assertFalse(pol.isProtocolAllowed(SCP02_15));
    Assert.assertFalse(pol.isProtocolAllowed(SCP02_55));
    pol.checkProtocol(SCP01_05);
    pol.checkProtocol(SCP01_15);
}
 
Example #25
Source File: PkgList.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void performOperation(OJCPackageManager manager) throws CardException {
    List<OJCPackage> packages = manager.getAvailablePackages();
    for(OJCPackage pkg: packages) {

    }
}
 
Example #26
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void performDelete(AID aid, boolean deleteRelated) throws CardException {
    LOG.trace("performDelete()");
    // pack up the AID in a TLV
    byte[] tlv = aid.getTLVBytes();
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_DELETE,
            (byte) 0,
            deleteRelated ? GP.DELETE_P2_DELETE_RELATED
                          : GP.DELETE_P2_DELETE_INDICATED,
            tlv);
    // and execute it
    transactSecureAndCheck(command);
}
 
Example #27
Source File: SCPSecurityPolicyTest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCENCAccept() throws CardException {
    SCPSecurityPolicy pol = SCPSecurityPolicy.CENC;
    pol.checkProtocol(SCP01_05);
    pol.checkProtocol(SCP01_15);
    pol.checkProtocol(SCP02_15);
    pol.checkProtocol(SCP02_55);
    pol.checkProtocol(SCP03_10);
    pol.checkProtocol(SCP03_30);
    pol.checkProtocol(SCP03_70);
}
 
Example #28
Source File: SCPProtocolPolicyTest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testSCP02Accept() throws CardException {
    SCPProtocolPolicy pol = SCPProtocolPolicy.SCP02;
    Assert.assertFalse(pol.isVersionAllowed(0x01));
    Assert.assertTrue(pol.isVersionAllowed(0x02));
    Assert.assertFalse(pol.isVersionAllowed(0x03));
    Assert.assertTrue(pol.isProtocolAllowed(0x02, 0x15));
    Assert.assertTrue(pol.isProtocolAllowed(0x02, 0x55));
    pol.checkProtocol(SCP02_15);
    pol.checkProtocol(SCP02_55);
}
 
Example #29
Source File: SCP02WrapperTest.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void test_SCP02_15_EncryptSensitive() throws CardException {
    SCP0102Wrapper wrap = new SCP0102Wrapper(GPKeySet.GLOBALPLATFORM, SCP02_15);
    byte [] encNUL = wrap.encryptSensitiveData(new byte[16]);
    System.out.println("encNUL " + HexUtil.bytesToHex(encNUL));
    Assert.assertArrayEquals(HexUtil.hexToBytes("8baf473f2f8fd0948baf473f2f8fd094"), encNUL);
    byte [] encGP = wrap.encryptSensitiveData(GPKey.GLOBALPLATFORM_MASTER_SECRET);
    System.out.println("encGP " + HexUtil.bytesToHex(encGP));
    Assert.assertArrayEquals(HexUtil.hexToBytes("b4baa89a8cd0292b45210e1bc84b1c31"), encGP);
}
 
Example #30
Source File: ChannelImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static int getSW(byte[] res) throws CardException {
   if (res.length < 2) {
      throw new CardException("Invalid response length: " + res.length);
   } else {
      int sw1 = res[res.length - 2] & 255;
      int sw2 = res[res.length - 1] & 255;
      return sw1 << 8 | sw2;
   }
}