javax.smartcardio.ResponseAPDU Java Examples

The following examples show how to use javax.smartcardio.ResponseAPDU. 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: GpgDataTest.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void writePWStatus() throws CardException {
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x82, "31 32 33 34 35 36"));
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 38"));

  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_PUT_DATA, 0, 0xC4, "00"));
  ResponseAPDU response = assertSW(0x9000, card.sendAPDU(0, Gpg.CMD_GET_DATA, 0, 0xC4, 7));
  assertEquals(0, response.getData()[0]);
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_PUT_DATA, 0, 0xC4, "01"));
  ResponseAPDU response2 = assertSW(0x9000, card.sendAPDU(0, Gpg.CMD_GET_DATA, 0, 0xC4, 7));
  assertEquals(1, response2.getData()[0]);
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_PUT_DATA, 0, 0xC4, "00 FF FF FF FF FF FF FF"));
  response2 = assertSW(0x9000, card.sendAPDU(0, Gpg.CMD_GET_DATA, 0, 0xC4, 7));
  assertArrayEquals(response.getData(), response2.getData());
  // Too long.
  assertSWOnly(0x6700, card.sendAPDU(0, Gpg.CMD_PUT_DATA, 0, 0xC4, "00 FF FF FF FF FF FF FF FF"));
  // Bad PIN3
  assertSWOnly(0x63C0 + Gpg.MAX_TRIES_PIN3 - 1,
               card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 37"));
  assertSWOnly(0x6982, card.sendAPDU(0, Gpg.CMD_PUT_DATA, 0, 0xC4, "00"));
  // Good PIN3
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 38"));
}
 
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: 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 #5
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 #6
Source File: APDUUtil.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Stringify a response APDU verbosely
 *
 * @param apdu to stringify
 * @return string representing the APDU
 */
public static String toString(ResponseAPDU apdu) {
    StringBuffer sb = new StringBuffer();
    int sw = apdu.getSW();
    sb.append("SW=" + HexUtil.hex16(sw));
    SWInfo swData = SWInfo.get(sw);
    if (swData != null) {
        sb.append(" [");
        sb.append(swData.name);
        sb.append("]");
    } else {
        sb.append(" [unknown]");
    }
    byte[] data = apdu.getData();
    if (data == null || data.length == 0) {
        sb.append(" (no data)");
    } else {
        sb.append(" LE=" + data.length);
        sb.append(" DATA=" + HexUtil.bytesToHex(data));
    }
    return sb.toString();
}
 
Example #7
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 #8
Source File: GpgCryptoTest.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void decryptWithCommandChaining() throws CardException {
  byte[] data = encodeCRTKey(0xB8, encryptionP, encryptionQ, encryptionDP1, encryptionDQ1,
                             encryptionPQ);
  // Submit PW3
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 38"));
  // Load the encrytion key.
  sendKey(data);
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x82, "31 32 33 34 35 36"));

  byte[] eData = toByteArray("00" + encryptedData);
  ResponseAPDU r = sendLong(0, Gpg.CMD_COMPUTE_PSO, 0x80, 0x86, eData, 250);
  assertArrayEquals("Expected: " + clearData, toByteArray(clearData), r.getData());

  eData = toByteArray("00" + encryptedData2);
  r = sendLong(0, Gpg.CMD_COMPUTE_PSO, 0x80, 0x86, eData, 250);
  assertArrayEquals("Expected: " + clearData2, toByteArray(clearData2), r.getData());
}
 
Example #9
Source File: Response.java    From ECTester with MIT License 6 votes vote down vote up
public GetInfo(ResponseAPDU response, String description, long time) {
    super(response, description, time);

    parse(1, 1);
    int offset = 2 + 2 + getParamLength(0);
    byte[] data = getData();
    base = ByteUtil.getShort(data, offset);
    offset += 2;
    jcVersion = ByteUtil.getShort(data, offset);
    offset += 2;
    cleanupSupport = ByteUtil.getShort(data, offset);
    offset += 2;
    apduBufferLength = ByteUtil.getShort(data, offset);
    offset += 2;
    ramArrayLength = ByteUtil.getShort(data, offset);
    offset += 2;
    ramArray2Length = ByteUtil.getShort(data, offset);
    offset += 2;
    apduArrayLength = ByteUtil.getShort(data, offset);
}
 
Example #10
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 #11
Source File: SmartcardTestService.java    From statelearner with Apache License 2.0 6 votes vote down vote up
public ResponseAPDU[] sendCommand(String command) throws Exception {
	// Look up APDU corresponding with given command
	byte[][] payloads = apduDictionary.get(command);
	
	if(payloads == null) {
		throw new Exception("Unknown command");
	}
	
	ResponseAPDU[] responses = new ResponseAPDU[payloads.length];
	
	for(int i = 0; i < payloads.length; i++) {
		responses[i] = sendAPDU(payloads[i]);
	}
	
	// Return responses from last command
	return responses;		
}
 
Example #12
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
public GPInstallForInstallResponse performInstallForInstall(GPInstallForInstallRequest request) throws CardException {
    LOG.trace("performInstallForInstall()");
    // serialize the request
    byte[] requestBytes = request.toBytes();
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_INSTALL,
            (byte)(GP.INSTALL_P1_FOR_INSTALL|GP.INSTALL_P1_FOR_MAKE_SELECTABLE),
            GP.INSTALL_P2_NO_INFORMATION,
            requestBytes);
    // perform the operation
    ResponseAPDU responseAPDU = transactSecureAndCheck(command);
    // parse and return response
    GPInstallForInstallResponse response = new GPInstallForInstallResponse();
    response.readBytes(responseAPDU.getData());
    return response;
}
 
Example #13
Source File: GpgCryptoTest.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void decrypt() throws CardException {
  byte[] data = encodeCRTKey(0xB8, encryptionP, encryptionQ, encryptionDP1, encryptionDQ1,
                             encryptionPQ);
  // Submit PW3
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x83, "31 32 33 34 35 36 37 38"));
  // Load the encrytion key.
  sendKey(data);
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x82, "31 32 33 34 35 36"));

  byte[] eData = toByteArray("00" + encryptedData);
  ResponseAPDU r = sendLong(0, Gpg.CMD_COMPUTE_PSO, 0x80, 0x86, eData, 255);
  assertArrayEquals("Expected: " + clearData, toByteArray(clearData), r.getData());

  clearCard();
  assertSWOnly(0x9000, card.sendAPDU(0, Gpg.CMD_VERIFY, 0, 0x81, "31 32 33 34 35 36"));
  // Check that the decrytion key is not operable.
  assertSWOnly(0x6A82, card.sendAPDU(0, Gpg.CMD_COMPUTE_PSO, 0x80, 0x86,
                                     Arrays.copyOfRange(eData, 0, 128)));
}
 
Example #14
Source File: GpgDataTest.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
private void checkCompositeData(byte[] compositeData) throws CardException {
  int pos = 0;
  while (pos < compositeData.length) {
    TLVDer tlv = TLVDer.GetNext(compositeData, pos);
    if (tlv.status == TLVDer.Status.END) {
      break;
    }
    assertEquals(TLVDer.Status.OK, tlv.status);
    DataObject cardObject = DataObject.getByTag(tlv.tag);
    assertNotNull("Unknown object returned:" + tlv.tag, cardObject);

    ResponseAPDU singleObject =
        assertSW(0x9000, card.sendAPDU(0, Gpg.CMD_GET_DATA, tlv.tag >> 8, tlv.tag & 0xFF, 0));
    assertArrayEquals("Expecting: " + bytesToHex(tlv.data), tlv.data, singleObject.getData());
    // We should never get currentOffset == pos since we need at least a byte for the tag and
    // another for the length.
    assertNotEquals(pos, tlv.currentOffset);
    pos = tlv.currentOffset;
  }
}
 
Example #15
Source File: CardManager.java    From JCMathLib with MIT License 5 votes vote down vote up
private void log(ResponseAPDU response, long time) {
    String swStr = String.format("%02X", response.getSW());
    byte[] data = response.getData();
    if (data.length > 0) {
        System.out.printf("<-- %s %s (%d) [%d ms]\n", Util.toHex(data), swStr,
                data.length, time);
    } else {
        System.out.printf("<-- %s [%d ms]\n", swStr, time);
    }
}
 
Example #16
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Response.Allocate send() throws CardException {
    long elapsed = -System.nanoTime();
    ResponseAPDU response = cardManager.send(cmd);
    elapsed += System.nanoTime();
    return new Response.Allocate(response, getDescription(), elapsed, keyPair, keyLength, keyClass);
}
 
Example #17
Source File: PCSCUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private static ResponseAPDU verifyPIN(char[] pin) throws CardException {
   byte[] verifyData = new byte[]{(byte)(32 | pin.length), -1, -1, -1, -1, -1, -1, -1};

   for(int idx = 0; idx < pin.length; idx += 2) {
      char digit1 = pin[idx];
      char digit2;
      if (idx + 1 < pin.length) {
         digit2 = pin[idx + 1];
      } else {
         digit2 = '?';
      }

      byte value = (byte)((digit1 - 48 << 4) + (digit2 - 48));
      verifyData[idx / 2 + 1] = value;
   }

   Arrays.fill(pin, '\u0000');
   LOG.debug("verifying PIN...");

   ResponseAPDU var9;
   try {
      var9 = transmit(new CommandAPDU(0, 32, 0, 1, verifyData));
   } finally {
      Arrays.fill(verifyData, (byte)0);
   }

   return var9;
}
 
Example #18
Source File: Response.java    From ECTester with MIT License 5 votes vote down vote up
public ECDSA(ResponseAPDU response, String description, long time, byte keyPair, byte sigType, byte export, byte[] raw) {
    super(response, description, time);
    this.keyPair = keyPair;
    this.sigType = sigType;
    this.export = export;
    this.raw = raw;

    parse(1, (export == ECTesterApplet.EXPORT_TRUE) ? 1 : 0);
}
 
Example #19
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Response.Set send() throws CardException {
    long elapsed = -System.nanoTime();
    ResponseAPDU response = cardManager.send(cmd);
    elapsed += System.nanoTime();
    return new Response.Set(response, getDescription(), elapsed, keyPair, curve, params);
}
 
Example #20
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Response.GetInfo send() throws CardException {
    long elapsed = -System.nanoTime();
    ResponseAPDU response = cardManager.send(cmd);
    elapsed += System.nanoTime();
    return new Response.GetInfo(response, getDescription(), elapsed);
}
 
Example #21
Source File: TestClient.java    From JCMathLib with MIT License 5 votes vote down vote up
static boolean verifyAndLogResponse(String operationName, ResponseAPDU response, Long lastTransmitTime, ECPoint expected, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {
    boolean bResult = false;
    if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {
        bResult = Arrays.equals(expected.getEncoded(false), response.getData());
        if (!bResult) {
            System.out.println(String.format("Expected: %s", Util.toHex(expected.getEncoded(false))));
            System.out.println(String.format("Obtained: %s", Util.toHex(response.getData())));
        }
    } else {
        bResult = false;
        System.out.println(String.format("fail (0x%x)", response.getSW()));
    }
    logResponse(operationName, bResult, lastTransmitTime, perfFile, failedTestsList);
    return bResult;
}
 
Example #22
Source File: ScanName.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ResponseAPDU performSelect(GenericCard card, byte[] aid, boolean first) throws CardException {
    byte p1 = ISO7816.SELECT_P1_BY_NAME;
    byte p2 = first ? ISO7816.SELECT_P2_FIRST_OR_ONLY : ISO7816.SELECT_P2_NEXT;
    CommandAPDU scapdu = APDUUtil.buildCommand(
            ISO7816.CLA_ISO7816, ISO7816.INS_SELECT,
            p1, p2, aid);
    return card.transmit(scapdu);
}
 
Example #23
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 #24
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 #25
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Response.Cleanup send() throws CardException {
    long elapsed = -System.nanoTime();
    ResponseAPDU response = cardManager.send(cmd);
    elapsed += System.nanoTime();
    return new Response.Cleanup(response, getDescription(), elapsed);
}
 
Example #26
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Response.Transform send() throws CardException {
    long elapsed = -System.nanoTime();
    ResponseAPDU response = cardManager.send(cmd);
    elapsed += System.nanoTime();
    return new Response.Transform(response, getDescription(), elapsed, keyPair, key, params, transformation);
}
 
Example #27
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void transmitTestCommand(CardChannel channel) throws Exception {
    ResponseAPDU r = channel.transmit(new CommandAPDU(C1));
    byte[] rb = r.getBytes();
    if ((Arrays.equals(rb, R1a) == false) && (Arrays.equals(rb, R1b) == false)) {
        System.out.println("expected: " + toString(R1a));
        System.out.println("received: " + toString(rb));
        throw new Exception("Response does not match");
    }
}
 
Example #28
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 #29
Source File: CardManager.java    From JCMathLib with MIT License 5 votes vote down vote up
private void log(ResponseAPDU response, long time) {
    String swStr = String.format("%02X", response.getSW());
    byte[] data = response.getData();
    if (data.length > 0) {
        System.out.printf("<-- %s %s (%d) [%d ms]\n", toHex(data), swStr,
                data.length, time);
    } else {
        System.out.printf("<-- %s [%d ms]\n", swStr, time);
    }
}
 
Example #30
Source File: SimulatedCardChannelLocal.java    From JCMathLib with MIT License 5 votes vote down vote up
@Override
public ResponseAPDU transmit(CommandAPDU apdu) throws CardException {
    ResponseAPDU responseAPDU = null;

    try {
        responseAPDU = this.m_simulator.transmitCommand(apdu);
        // TODO: Add delay corresponding to real cards
        //int delay = OperationTimes.getCardOperationDelay(apdu);
        //Thread.sleep(delay);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return responseAPDU;
}