javax.smartcardio.CommandAPDU Java Examples

The following examples show how to use javax.smartcardio.CommandAPDU. 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: APDUUtil.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Stringify a command APDU verbosely
 *
 * @param apdu to stringify
 * @return string representing the APDU
 */
public static String toString(CommandAPDU apdu) {
    byte[] data = apdu.getData();
    String dataString = " (no data)";
    if (data != null) {
        int dataLength = data.length;
        if (dataLength > 0) {
            dataString = " LC=" + HexUtil.hex8(dataLength)
                    + " DATA=" + HexUtil.bytesToHex(data);
        }
    }
    String p12 = HexUtil.bytesToHex(
            new byte[]{
                    (byte) apdu.getP1(),
                    (byte) apdu.getP2()}
    );
    return "CLA=" + HexUtil.hex8(apdu.getCLA())
            + " INS=" + HexUtil.hex8(apdu.getINS())
            + " P12=" + p12
            + dataString
            + " LE=" + apdu.getNe();
}
 
Example #3
Source File: Command.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * Creates the INS_SET instruction.
 *
 * @param cardManager cardManager to send APDU through
 * @param keyPair     which keyPair to set params on, local/remote (KEYPAIR_* || ...)
 * @param curve       curve to set (EC_Consts.CURVE_*)
 * @param params      parameters to set (EC_Consts.PARAMETER_* | ...)
 * @param external    external curve data, can be null
 */
public Set(CardMngr cardManager, byte keyPair, byte curve, short params, byte[] external) {
    super(cardManager);
    this.keyPair = keyPair;
    this.curve = curve;
    this.params = params;
    this.external = external;

    int len = external != null ? 2 + external.length : 2;
    byte[] data = new byte[len];
    ByteUtil.setShort(data, 0, params);
    if (external != null) {
        System.arraycopy(external, 0, data, 2, external.length);
    }

    this.cmd = new CommandAPDU(ECTesterApplet.CLA_ECTESTERAPPLET, ECTesterApplet.INS_SET, keyPair, curve, data);
}
 
Example #4
Source File: Command.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * Creates the INS_ECDSA_VERIFY instruction.
 *
 * @param cardManager cardManager to send APDU through
 * @param keyPair     keyPair to use for signing and verification (KEYPAIR_LOCAL || KEYPAIR_REMOTE)
 * @param sigType     Signature type to use
 * @param raw         data to sign
 * @param signature   signature data
 */
public ECDSA_verify(CardMngr cardManager, byte keyPair, byte sigType, byte[] raw, byte[] signature) {
    super(cardManager);
    if (keyPair == ECTesterApplet.KEYPAIR_BOTH) {
        throw new IllegalArgumentException();
    }
    if (raw == null || signature == null) {
        throw new IllegalArgumentException();
    }

    this.keyPair = keyPair;
    this.sigType = sigType;
    this.raw = raw;
    this.signature = signature;

    byte[] data = new byte[4 + raw.length + signature.length];
    ByteUtil.setShort(data, 0, (short) raw.length);
    System.arraycopy(raw, 0, data, 2, raw.length);
    ByteUtil.setShort(data, 2 + raw.length, (short) signature.length);
    System.arraycopy(signature, 0, data, 2 + raw.length + 2, signature.length);

    this.cmd = new CommandAPDU(ECTesterApplet.CLA_ECTESTERAPPLET, ECTesterApplet.INS_ECDSA_VERIFY, keyPair, sigType, data);
}
 
Example #5
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
public GPInstallForPersonalizeResponse performInstallForPersonalize(GPInstallForPersonalizeRequest request) throws CardException {
    LOG.trace("performInstallForPersonalize()");
    // serialize the request
    byte[] requestBytes = request.toBytes();
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_INSTALL,
            GP.INSTALL_P1_FOR_PERSONALIZATION,
            GP.INSTALL_P2_NO_INFORMATION,
            requestBytes);
    // perform the operation
    ResponseAPDU responseAPDU = transactSecureAndCheck(command);
    // parse and return response
    GPInstallForPersonalizeResponse response = new GPInstallForPersonalizeResponse();
    response.readBytes(responseAPDU.getData());
    return response;
}
 
Example #6
Source File: GlobalPlatformCard.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean reinstallApplet(byte[] aid) throws CardException {
  logger.info("[Reinstalling the applet]");
  int keySet = 0;
  byte[][] keys = { GlobalPlatformService.defaultEncKey, GlobalPlatformService.defaultMacKey,
                    GlobalPlatformService.defaultKekKey };

  GlobalPlatformService service = new GlobalPlatformService(
      new AID(opSecurityDomainAID), channel);

  service.addAPDUListener(this);
  service.open();
  service.setKeys(keySet, GlobalPlatformService.defaultEncKey,
                  GlobalPlatformService.defaultMacKey, GlobalPlatformService.defaultKekKey,
                  GlobalPlatformService.DIVER_NONE);

  service.openSecureChannel(keySet, 0,
                            GlobalPlatformService.SCP_ANY,
                            GlobalPlatformService.APDU_MAC, false);

  service.deleteAID(new AID(aid), true);
  service.installAndMakeSelecatable(new AID(packageAID), new AID(aid), new AID(aid),
                                    installPrivileges, installParams, null);

  return loggedAPDU(new CommandAPDU(0, 0xA4, 4, 0, aid)).getSW() == 0x9000;
}
 
Example #7
Source File: CardUtils.java    From OpenPGP-Card with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a human friendly representation of a @CommandAPDU.
 */
public static String formatCommandAPDU(CommandAPDU command) {
  if (command.getNc() > 0) {
    if (command.getNe() > 0) {
      return format("[Sent] %02X %02X %02X %02X Lc = %02X Le = %02X ", command.getCLA(),
                    command.getINS(), command.getP1(), command.getP2(), command.getNc(),
                    command.getNe())
             + HexString.bytesToHex(command.getData());
    } else {
      return format("[Sent] %02X %02X %02X %02X %02X  ", command.getCLA(),
                    command.getINS(), command.getP1(), command.getP2(), command.getNc())
             + HexString.bytesToHex(command.getData());
    }
  } else {
    return format("[Sent] %02X %02X %02X %02X %02X  ", command.getCLA(),
                  command.getINS(), command.getP1(), command.getP2(), command.getNe());
  }
}
 
Example #8
Source File: CommandAPDUTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "provider1")
public static void testHeaders(CommandAPDU cm) {
    assertEquals(cla, cm.getCLA());
    assertEquals(ins, cm.getINS());
    assertEquals(p1, cm.getP1());
    assertEquals(p2, cm.getP2());
}
 
Example #9
Source File: CommandAPDUTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "provider1")
public static void testHeaders(CommandAPDU cm) {
    assertEquals(cla, cm.getCLA());
    assertEquals(ins, cm.getINS());
    assertEquals(p1, cm.getP1());
    assertEquals(p2, cm.getP2());
}
 
Example #10
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 #11
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 #12
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
/**
 * Creates the INS_ALLOCATE_KA instruction.
 *
 * @param cardManager cardManager to send APDU through
 * @param kaType      which type of KeyAgreement to use
 */
public AllocateKeyAgreement(CardMngr cardManager, byte kaType) {
    super(cardManager);
    this.kaType = kaType;
    byte[] data = new byte[]{kaType};
    this.cmd = new CommandAPDU(ECTesterApplet.CLA_ECTESTERAPPLET, ECTesterApplet.INS_ALLOCATE_KA, 0x00, 0x00, data);
}
 
Example #13
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 #14
Source File: CommandAPDUTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "provider1")
public static void testHeaders(CommandAPDU cm) {
    assertEquals(cla, cm.getCLA());
    assertEquals(ins, cm.getINS());
    assertEquals(p1, cm.getP1());
    assertEquals(p2, cm.getP2());
}
 
Example #15
Source File: Utils.java    From openjdk-jdk8u-backup 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 #16
Source File: CommandAPDUTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "provider1")
public static void testHeaders(CommandAPDU cm) {
    assertEquals(cla, cm.getCLA());
    assertEquals(ins, cm.getINS());
    assertEquals(p1, cm.getP1());
    assertEquals(p2, cm.getP2());
}
 
Example #17
Source File: Utils.java    From jdk8u-jdk 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 #18
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
/**
 * Creates the INS_EXPORT instruction.
 *
 * @param cardManager cardManager to send APDU through
 * @param keyPair     keyPair to export from (KEYPAIR_* | ...)
 * @param key         key to export from (EC_Consts.KEY_* | ...)
 * @param params      params to export (EC_Consts.PARAMETER_* | ...)
 */
public Export(CardMngr cardManager, byte keyPair, byte key, short params) {
    super(cardManager);
    this.keyPair = keyPair;
    this.key = key;
    this.params = params;

    byte[] data = new byte[2];
    ByteUtil.setShort(data, 0, params);

    this.cmd = new CommandAPDU(ECTesterApplet.CLA_ECTESTERAPPLET, ECTesterApplet.INS_EXPORT, keyPair, key, data);
}
 
Example #19
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
private ResponseAPDU execute(String Command, boolean display) {

        Command = Command.replaceAll("\\s","");
        if (display) System.out.println(Command);
        ResponseAPDU response = simulator.transmitCommand(new CommandAPDU(DatatypeConverter.parseHexBinary(Command)));
        if (display) System.out.println(DatatypeConverter.printHexBinary(response.getBytes()));
        return response;
    }
 
Example #20
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 #21
Source File: Utils.java    From dragonwell8_jdk 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 #22
Source File: Utils.java    From jdk8u-jdk 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 #23
Source File: Utils.java    From openjdk-jdk8u 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 #24
Source File: Command.java    From ECTester with MIT License 5 votes vote down vote up
/**
 * @param cardManager cardManager to send APDU through
 * @param keyPair     which keyPair clear, local/remote (KEYPAIR_* || ...)
 */
public Clear(CardMngr cardManager, byte keyPair) {
    super(cardManager);
    this.keyPair = keyPair;

    this.cmd = new CommandAPDU(ECTesterApplet.CLA_ECTESTERAPPLET, ECTesterApplet.INS_CLEAR, keyPair, 0x00, GOD_DAMN_JAVA_BUG_6474858_AND_GOD_DAMN_JAVA_12_MODULE_SYSTEM);
}
 
Example #25
Source File: GPSecureChannel.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Assemble and transact an EXTERNAL AUTHENTICATE command
 * <p/>
 * The command will be sent on the encrypted secure channel.
 * <p/>
 * @param hostCryptogram to send
 * @throws CardException on error
 */
private void performExternalAuthenticate(byte[] hostCryptogram) throws CardException {
    LOG.trace("performExternalAuthenticate()");
    // determine session parameters
    byte authParam = 0;
    // even CMAC can be optional for us
    if (mSecurityPolicy.requireCMAC)
        authParam |= GP.EXTERNAL_AUTHENTICATE_P1_MAC;
    // ENC, RMAC and RENC are optional
    if (mSecurityPolicy.requireCENC)
        authParam |= GP.EXTERNAL_AUTHENTICATE_P1_ENC;
    if (mSecurityPolicy.requireRMAC)
        authParam |= GP.EXTERNAL_AUTHENTICATE_P1_RMAC;
    if (mSecurityPolicy.requireRENC)
        authParam |= GP.EXTERNAL_AUTHENTICATE_P1_RENC;
    // build the command
    CommandAPDU authCommand = APDUUtil.buildCommand(
            GP.CLA_MAC,
            GP.INS_EXTERNAL_AUTHENTICATE,
            authParam,
            (byte) 0,
            hostCryptogram
    );
    // send it over the secure channel
    ResponseAPDU authResponse = transmitInternal(authCommand);
    // check for errors
    checkResponse(authResponse);
    // nothing to return
}
 
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 performSetStatusISD(AID aid, byte state) throws CardException {
    LOG.trace("performSetStatusISD()");
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_SET_STATUS,
            GP.SET_STATUS_FOR_ISD,
            state,
            aid.getBytes()
    );
    // execute it
    transactSecureAndCheck(command);
}
 
Example #27
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void performSetStatusApp(AID aid, byte state) throws CardException {
    LOG.trace("performSetStatusApp()");
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_SET_STATUS,
            GP.SET_STATUS_FOR_SSD_OR_APP,
            state,
            aid.getBytes()
    );
    // execute it
    transactSecureAndCheck(command);
}
 
Example #28
Source File: GPSecureWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void performSetStatusDomain(AID aid, byte state) throws CardException {
    LOG.trace("performSetStatusDomain()");
    // build the command
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_GP,
            GP.INS_SET_STATUS,
            GP.SET_STATUS_FOR_SD_AND_APPS,
            state,
            aid.getBytes()
    );
    // execute it
    transactSecureAndCheck(command);
}
 
Example #29
Source File: GPBasicWrapper.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Perform an ISO SELECT FILE BY NAME operation
 *
 * @param name in the form of an AID
 * @return response data
 * @throws CardException on error
 */
public byte[] selectFileByName(AID name) throws CardException {
    LOG.trace("selectFileByName(" + name + ")");
    CommandAPDU command = APDUUtil.buildCommand(
            GP.CLA_ISO,
            GP.INS_SELECT,
            GP.SELECT_P1_BY_NAME,
            GP.SELECT_P2_FIRST_OR_ONLY,
            name.getBytes()
    );
    return transactAndCheck(command).getData();
}
 
Example #30
Source File: Utils.java    From hottub 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");
    }
}