javacard.framework.ISO7816 Java Examples

The following examples show how to use javacard.framework.ISO7816. 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: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 9 votes vote down vote up
/**
 * Store the incoming APDU data in a fixed buffer, the first byte will contain the data length.
 *
 * @param pin_type indicates which PIN should be checked.
 */
void storeVariableLength(APDU apdu, byte[] destination, short pin_type) {
  byte[] buffer = apdu.getBuffer();
  // When writing DOs, PW1 really means PW1 submitted as PW2.
  if (!pins[pin_type].isValidated() ||
      ((pin_type == PIN_INDEX_PW1) && !pinSubmitted[1])) {
    ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
  }
  short length = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
  if ((short) (length + 1) > destination.length || length > (short) 255 ||
      apdu.setIncomingAndReceive() != length) {
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
  }
  JCSystem.beginTransaction();
  destination[0] = (byte) length;
  Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, destination, (short) 1, length);
  JCSystem.commitTransaction();
}
 
Example #2
Source File: TestTransaction.java    From ledger-javacard with GNU Affero General Public License v3.0 6 votes vote down vote up
public void testTX2ContactlessNoChange() throws BTChipException {
	KeycardHelper keycardHelper = new KeycardHelper(DEFAULT_KEYCARD);
	BTChipDongle dongle = prepareDongleRestoreTestnet(true);
	simulator.changeProtocol("T=CL,TYPE_A,T1");
	dongle.verifyPin(DEFAULT_PIN);
	BitcoinTransaction txin_1 = new BitcoinTransaction(new ByteArrayInputStream(TXIN_2_1));
	BitcoinTransaction txin_2 = new BitcoinTransaction(new ByteArrayInputStream(TXIN_2_2));
	BitcoinTransaction txout_1 = new BitcoinTransaction(new ByteArrayInputStream(TXOUT_2));
	BTChipDongle.BTChipInput input1 = dongle.getTrustedInput(txin_1, 1);
	BTChipDongle.BTChipInput input2 = dongle.getTrustedInput(txin_2, 0);
	dongle.startUntrustedTransaction(
		true, 
		0, 
		new BTChipDongle.BTChipInput[] { input1, input2 }, 
		txin_1.getOutputs().get(1).getScript());
	try {
		dongle.finalizeInputFull(txout_1.serializeOutputs());		
		fail();
	}
	catch(BTChipException e) {
		assertEquals(e.getSW(), ISO7816.SW_WRONG_DATA);
	}				
}
 
Example #3
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Attempt to connect to the backend service
 */
private void connectService() {
    NdefService service = null;
    // get AID object for service
    AID aid = JCSystem.lookupAID(serviceAID, (short)0, (byte)serviceAID.length);
    if(aid != null) {
        // get service object
        Shareable share = JCSystem.getAppletShareableInterfaceObject(aid, serviceID);
        // cast the service object
        if(share instanceof NdefService) {
            service = (NdefService)share;
        }
    }
    // check that we got a valid object
    if(service == null) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    // retrieve the data array
    byte[] data = service.getData();
    if(data == null) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    // remember both references
    refs[REF_SERVICE] = service;
    refs[REF_DATA] = data;
}
 
Example #4
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_BN_EXP(APDU apdu, short dataLen) {
    byte[] apdubuf = apdu.getBuffer();
    short p1 = (short) (apdubuf[ISO7816.OFFSET_P1] & 0x00FF);
    short p2 = (short) (apdubuf[ISO7816.OFFSET_P2] & 0x00FF);

    PM.check(PM.TRAP_BN_EXP_1);    
    Bignat base = m_testBN1;
    base.set_size(p1);
    PM.check(PM.TRAP_BN_EXP_2);
    Bignat exp = m_testBN2;
    exp.set_size((short) (dataLen - p1));
    PM.check(PM.TRAP_BN_EXP_3);
    Bignat res = m_testBN3;
    res.set_size((short) (m_ecc.MAX_BIGNAT_SIZE / 2));
    PM.check(PM.TRAP_BN_EXP_4);
    base.from_byte_array(p1, (short) 0, apdubuf, ISO7816.OFFSET_CDATA);
    exp.from_byte_array((short) (dataLen - p1), (short) 0, apdubuf, (short)(ISO7816.OFFSET_CDATA+p1));
    PM.check(PM.TRAP_BN_EXP_5);
    res.exponentiation(base, exp);
    PM.check(PM.TRAP_BN_EXP_6);
    short len = res.copy_to_buffer(apdubuf, (short) 0);
    apdu.setOutgoingAndSend((short) 0, len);
}
 
Example #5
Source File: IsoApplet.java    From IsoApplet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * \brief Process the PERFORM SECURITY OPERATION apdu (INS=2A).
 *
 * This operation is used for cryptographic operations
 * (Computation of digital signatures, decrypting.).
 *
 * \param apdu The PERFORM SECURITY OPERATION apdu.
 *
 * \throw ISOException SW_SECURITY_STATUS_NOT_SATISFIED, SW_INCORRECT_P1P2 and
 * 			the ones from computeDigitalSignature() and decipher().
 */
private void processPerformSecurityOperation(APDU apdu) throws ISOException {
    byte[] buf = apdu.getBuffer();
    byte p1 = buf[ISO7816.OFFSET_P1];
    byte p2 = buf[ISO7816.OFFSET_P2];

    if( ! pin.isValidated() ) {
        ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    }

    if(p1 == (byte) 0x9E && p2 == (byte) 0x9A) {
        computeDigitalSignature(apdu);
    } else if(p1 == (byte) 0x80 && p2 == (byte) 0x86) {
        decipher(apdu);
    } else {
        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }

}
 
Example #6
Source File: ECKeyGenerator.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * @param keypair
 * @param key
 * @param params
 * @param transformation
 * @param buffer
 * @param offset
 * @return
 */
public short transformCurve(KeyPair keypair, byte key, short params, short transformation, byte[] buffer, short offset) {
    sw = ISO7816.SW_NO_ERROR;
    if (params == EC_Consts.PARAMETERS_NONE) {
        return sw;
    }

    //go through param bit by bit, and invalidate all selected params
    short paramMask = EC_Consts.PARAMETER_FP;
    while (paramMask <= EC_Consts.PARAMETER_S) {
        short masked = (short) (paramMask & params);
        if (masked != 0) {
            short length = exportParameter(keypair, key, masked, buffer, offset);
            length = EC_Consts.transformParameter(transformation, buffer, offset, length);
            sw = setParameter(keypair, key, masked, buffer, offset, length);
            if (sw != ISO7816.SW_NO_ERROR) break;
        }
        paramMask = (short) (paramMask << 1);
    }
    return sw;
}
 
Example #7
Source File: TransactionVerificationLog.java    From CardExamples with The Unlicense 6 votes vote down vote up
public TransactionVerificationLog(String accountParametersIndex, 
                                  byte transactionType, 
                                  String unpredictableNumber) throws ISOException {
    if ((accountParametersIndex != null) && 
        ((transactionType == TRANSACTION_TYPE_MSD) || 
         ((transactionType == TRANSACTION_TYPE_QVSDC) && (unpredictableNumber != null)))) {
        this.utcTimestamp = Calendar.getInstance().getTimeInMillis();

        this.acctParamIndex = accountParametersIndex;
        this.transactionType = transactionType;
        this.un = unpredictableNumber;
    }
    else {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }
}
 
Example #8
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_BN_ADD_MOD(APDU apdu, short dataLen) {
    byte[] apdubuf = apdu.getBuffer();
    short p1 = (short) (apdubuf[ISO7816.OFFSET_P1] & 0x00FF);
    short p2 = (short) (apdubuf[ISO7816.OFFSET_P2] & 0x00FF);

    PM.check(PM.TRAP_BN_ADD_MOD_1);    
    Bignat num1 = m_testBN1;
    num1.set_size(p1);
    PM.check(PM.TRAP_BN_ADD_MOD_2);
    Bignat num2 = m_testBN2;
    num2.set_size(p2);
    PM.check(PM.TRAP_BN_ADD_MOD_3);
    Bignat mod = m_testBN3;
    mod.set_size((short) (dataLen - p1 - p2));
    PM.check(PM.TRAP_BN_ADD_MOD_4);
    num1.from_byte_array(p1, (short)0, apdubuf, ISO7816.OFFSET_CDATA);
    num2.from_byte_array(p2, (short)0, apdubuf, (short)(ISO7816.OFFSET_CDATA+p1));
    PM.check(PM.TRAP_BN_ADD_MOD_5);
    mod.from_byte_array((short)(dataLen-p1-p2), (short)0, apdubuf, (short)(ISO7816.OFFSET_CDATA+p1+p2));
    PM.check(PM.TRAP_BN_ADD_MOD_6);
    num1.mod_add(num2, mod);
    PM.check(PM.TRAP_BN_ADD_MOD_7);
    short len = num1.copy_to_buffer(apdubuf, (short) 0);
    apdu.setOutgoingAndSend((short) 0, len);
}
 
Example #9
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Access a file for writing
 *
 * This function serves to perform precondition checks
 * before actually operating on a file in a write operation.
 *
 * If this function succeeds then the given fileId was
 * valid, security access has been granted and writing
 * of data for this file is possible.
 *
 * @param fileId of the file to be written
 * @return data array of the file
 * @throws ISOException on error
 */
private byte[] accessFileForWrite(short fileId) throws ISOException {
    byte[] file = null;
    byte access = FILE_ACCESS_NONE;
    // CC can not be written
    if(fileId == FILEID_NDEF_CAPABILITIES) {
        ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
    }
    // select relevant data
    if(fileId == FILEID_NDEF_DATA) {
        file = dataFile;
        access = dataWriteAccess;
    }
    // check that we got something
    if(file == null) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    // perform access checks
    if(!checkAccess(file, access)) {
        ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    }
    return file;
}
 
Example #10
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_BN_POW2_MOD(APDU apdu, short dataLen) {
    byte[] apdubuf = apdu.getBuffer();
    short p1 = (short) (apdubuf[ISO7816.OFFSET_P1] & 0x00FF);
    short p2 = (short) (apdubuf[ISO7816.OFFSET_P2] & 0x00FF);

    PM.check(PM.TRAP_BN_POW2_MOD_1);
    Bignat num1 = m_testBN1;
    num1.set_size(p1);
    Bignat mod = m_testBN3;
    mod.set_size((short) (dataLen - p1));
    num1.from_byte_array(p1, (short) 0, apdubuf, ISO7816.OFFSET_CDATA);
    mod.from_byte_array((short) (dataLen - p1), (short) 0, apdubuf, (short) (ISO7816.OFFSET_CDATA + p1));
    PM.check(PM.TRAP_BN_POW2_MOD_2);
    //num1.pow2Mod_RSATrick(mod);
    num1.mod_exp2(mod);
    PM.check(PM.TRAP_BN_POW2_MOD_3);
    short len = num1.copy_to_buffer(apdubuf, (short) 0);
    apdu.setOutgoingAndSend((short) 0, len);
}
 
Example #11
Source File: TransactionVerificationLog.java    From CardExamples with The Unlicense 6 votes vote down vote up
public TransactionVerificationLog(String accountParametersIndex, 
                                  byte transactionType, 
                                  String unpredictableNumber) throws ISOException {
    if ((accountParametersIndex != null) && 
        ((transactionType == TRANSACTION_TYPE_MSD) || 
         ((transactionType == TRANSACTION_TYPE_QVSDC) && (unpredictableNumber != null)))) {
        this.utcTimestamp = Calendar.getInstance().getTimeInMillis();

        this.acctParamIndex = accountParametersIndex;
        this.transactionType = transactionType;
        this.un = unpredictableNumber;
    }
    else {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }
}
 
Example #12
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_INT_SUB(APDU apdu, short dataLen) {
    byte[] apdubuf = apdu.getBuffer();
    short p1 = (short) (apdubuf[ISO7816.OFFSET_P1] & 0x00FF);

    PM.check(PM.TRAP_INT_SUB_1);               
    Integer num_sub_1 = m_testINT1;
    num_sub_1.fromByteArray(apdubuf, ISO7816.OFFSET_CDATA, p1);
    Integer num_sub_2 = m_testINT2;
    num_sub_2.fromByteArray(apdubuf, (short) (ISO7816.OFFSET_CDATA + p1), p1);
    PM.check(PM.TRAP_INT_SUB_2);

    num_sub_1.subtract(num_sub_2);
    PM.check(PM.TRAP_INT_SUB_3);
    short len = num_sub_1.toByteArray(apdubuf, (short) 0);
    apdu.setOutgoingAndSend((short) 0, len);
}
 
Example #13
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Access a file for reading
 *
 * This function serves to perform precondition checks
 * before actually operating on a file in a read operation.
 *
 * If this function succeeds then the given fileId was
 * valid, security access has been granted and reading
 * of data for this file is possible.
 *
 * @param fileId of the file to be read
 * @return data array of the file
 * @throws ISOException on error
 */
private byte[] accessFileForRead(short fileId) throws ISOException {
    byte[] file = null;
    byte access = FILE_ACCESS_NONE;
    // select relevant data
    if(fileId == FILEID_NDEF_CAPABILITIES) {
        file = capsFile;
        access = FILE_ACCESS_OPEN;
    }
    if(fileId == FILEID_NDEF_DATA) {
        file = dataFile;
        access = dataReadAccess;
    }
    // check that we got anything
    if(file == null) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }
    // perform access checks
    if(!checkAccess(file, access)) {
        ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    }
    return file;
}
 
Example #14
Source File: ECKeyGenerator.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * Exports selected parameters from a given keyPairs key.
 * Raw parameter data is always prepended by its length as a
 * short value. The order of parameters is the usual one from
 * EC_Consts: field,a,b,g,r,k,w,s.
 *
 * @param keypair keyPair to export from
 * @param key     key to export from (KEY_PUBLIC || KEY_PRIVATE)
 * @param params  params to export (EC_Consts.PARAMETER_* | ...)
 * @param buffer  buffer to export to
 * @param offset  offset to start writing in buffer
 * @return length of data written
 */
public short exportParameters(KeyPair keypair, byte key, short params, byte[] buffer, short offset) {
    sw = ISO7816.SW_NO_ERROR;
    if (params == EC_Consts.PARAMETERS_NONE) {
        return sw;
    }

    short length = 0;
    short paramMask = EC_Consts.PARAMETER_FP;
    while (paramMask <= EC_Consts.PARAMETER_S) {
        short masked = (short) (paramMask & params);
        if (masked != 0) {
            short len = exportParameter(keypair, key, masked, buffer, (short) (offset + 2));
            if (len == 0) {
                paramMask = (short) (paramMask << 1);
                continue;
            }
            Util.setShort(buffer, offset, len);
            offset += len + 2;
            length += len + 2;
        }
        paramMask = (short) (paramMask << 1);
    }
    return length;
}
 
Example #15
Source File: GenericBEHelper.java    From ledger-javacard with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sub(byte size, byte[] target, short targetOffset, byte[] a, short aOffset, byte[] b, short bOffset) {
    boolean borrow = false;
    for (byte i=0; i<size; i++) {
        short tmpA = (short)(a[(short)(aOffset + size - 1 - i)] & 0xff);
        short tmpB = (short)(b[(short)(bOffset + size - 1 - i)] & 0xff);
        if (borrow) {
            if (tmpA <= tmpB) {
                tmpA += (255 + 1) - 1;
            }
            else {
                borrow = false;
                tmpA--;
            }
        }
        if (tmpA < tmpB) {
            borrow = true;
            tmpA += 255 + 1;
        }
        target[(short)(targetOffset + size - 1 - i)] = (byte)(tmpA - tmpB);
    }
    if (borrow) {
        ISOException.throwIt(ISO7816.SW_WRONG_DATA);
    }
}
 
Example #16
Source File: TransitApplet.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
 * Gets/returns the balance.
 * 
 * Request Message: []
 * 
 * Response Message: [2-bytes Balance]
 * 
 * @param buffer
 *            The APDU buffer
 * @param messageOffset
 *            The offset of the request message content in the APDU buffer
 * @param messageLength
 *            The length of the request message content.
 * @return The offset at which content can be appended to the response
 *         message
 */
private short getBalance(byte[] buffer, short messageOffset,
        short messageLength) {

    // Check access authorization
    if (!pin.isValidated()) {
        ISOException.throwIt(SW_PIN_VERIFICATION_REQUIRED);
    }

    // Request Message: []

    if (messageLength != 0) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    // Response Message: [2-bytes Balance]

    short offset = 0;

    // Append balance to response message
    offset = Util.setShort(buffer, offset, balance);

    return offset;
}
 
Example #17
Source File: STPayP.java    From CardExamples with The Unlicense 6 votes vote down vote up
private void getMobileKey(APDU apdu) throws ISOException {
    byte[] apduBuffer = apdu.getBuffer();

    // Check if P1=0x00 and P2=0x00.
    if (Util.getShort(apduBuffer, ISO7816.OFFSET_P1) != (short) 0x0000) {
        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }

    short dataLength = apdu.setOutgoing();
    // Check if Le=0x00.
    if (dataLength != (short) 256) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    // Check if Mobile Key is initialized.
    if (!this.dataEncryption.isMobileKeyInit()) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }

    dataLength = this.dataEncryption.getMobileKey(apduBuffer, (short) 0);
    apdu.setOutgoingLength(dataLength);
    apdu.sendBytes((short) 0, dataLength);
}
 
Example #18
Source File: IsoApplet.java    From IsoApplet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * \brief Process the PUT DATA apdu (INS=DB).
 *
 * PUT DATA is currently used for private key import.
 *
 * \throw ISOException SW_SECURITY_STATUS_NOT_SATISFIED, SW_INCORRECT_P1P2
 */
private void processPutData(APDU apdu) throws ISOException {
    byte[] buf = apdu.getBuffer();
    byte p1 = buf[ISO7816.OFFSET_P1];
    byte p2 = buf[ISO7816.OFFSET_P2];

    if( ! pin.isValidated() ) {
        ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
    }

    if(p1 == (byte) 0x3F && p2 == (byte) 0xFF) {
        if( ! DEF_PRIVATE_KEY_IMPORT_ALLOWED) {
            ISOException.throwIt(SW_COMMAND_NOT_ALLOWED_GENERAL);
        }
        importPrivateKey(apdu);
    } else {
        ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
    }
}
 
Example #19
Source File: TestTransaction.java    From ledger-javacard with GNU Affero General Public License v3.0 6 votes vote down vote up
public void testTX1ContactlessUntrustedInput() throws BTChipException {
	KeycardHelper keycardHelper = new KeycardHelper(DEFAULT_KEYCARD);
	BTChipDongle dongle = prepareDongleRestoreTestnet(true);
	simulator.changeProtocol("T=CL,TYPE_A,T1");
	dongle.verifyPin(DEFAULT_PIN);
	BitcoinTransaction txin_1 = new BitcoinTransaction(new ByteArrayInputStream(TXIN_1));
	BitcoinTransaction txout_1 = new BitcoinTransaction(new ByteArrayInputStream(TXOUT_1));
	BTChipDongle.BTChipInput input1 = dongle.getTrustedInput(txin_1, 1);
	byte[] prevout = Arrays.copyOfRange(input1.getValue(), 4, 4 + 36);
	input1 = dongle.createInput(prevout, false);
	try {
		dongle.startUntrustedTransaction(
			true, 
			0, 
			new BTChipDongle.BTChipInput[] { input1 }, 
			txin_1.getOutputs().get(1).getScript());
		fail();
	}
	catch(BTChipException e) {
		assertEquals(e.getSW(), ISO7816.SW_WRONG_DATA);
	}		
}
 
Example #20
Source File: TransitApplet.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
 * Verifies the PIN.
 * 
 * @param apdu
 *            The APDU
 */
private void verify(APDU apdu) {

    byte[] buffer = apdu.getBuffer();

    byte numBytes = buffer[ISO7816.OFFSET_LC];

    byte count = (byte) apdu.setIncomingAndReceive();

    if (numBytes != count) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    // Verify PIN
    if (pin.check(buffer, ISO7816.OFFSET_CDATA, numBytes) == false) {
        ISOException.throwIt(SW_VERIFICATION_FAILED);
    }
}
 
Example #21
Source File: PasswordManagerApplet.java    From sim-password-manager with Apache License 2.0 6 votes vote down vote up
private void prng(byte[] buff, short offset, short len) {
    if (len > AES_BLOCK_LEN) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    Util.arrayCopyNonAtomic(prngNonce, OFFSET_ZERO, cipherBuff,
            OFFSET_ZERO, (short) prngNonce.length);
    Util.setShort(cipherBuff, (short) (AES_BLOCK_LEN - 2), prngCounter);

    try {
        aesCipher.RoundKeysSchedule(prngKey, (short) 0, roundKeysBuff);

        // encrypts in place
        boolean success = aesCipher.AESEncryptBlock(cipherBuff,
                OFFSET_ZERO, roundKeysBuff);
        if (!success) {
            ISOException.throwIt(ISO7816.SW_DATA_INVALID);
        }
        prngCounter++;

        Util.arrayCopyNonAtomic(cipherBuff, OFFSET_ZERO, buff, offset, len);
    } finally {
        clearCipherState();
    }
}
 
Example #22
Source File: PasswordManagerApplet.java    From sim-password-manager with Apache License 2.0 6 votes vote down vote up
private static short padCount(byte[] in, short len) {
    short count = (short) (in[(short) (len - 1)] & 0xff);

    if (count > len || count == 0) {
        // corrupted pad block
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }

    for (short i = 1; i <= count; i++) {
        if (in[(short) (len - i)] != count) {
            // corrupted pad block
            ISOException.throwIt(ISO7816.SW_DATA_INVALID);
        }
    }

    return count;
}
 
Example #23
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_INT_MUL(APDU apdu, short dataLen) {
    byte[] apdubuf = apdu.getBuffer();
    short p1 = (short) (apdubuf[ISO7816.OFFSET_P1] & 0x00FF);

    PM.check(PM.TRAP_INT_MUL_1);    
    Integer num_mul_1 = m_testINT1;
    num_mul_1.fromByteArray(apdubuf, ISO7816.OFFSET_CDATA, p1);
    Integer num_mul_2 = m_testINT2;
    num_mul_2.fromByteArray(apdubuf, (short) (ISO7816.OFFSET_CDATA + p1), p1);
    PM.check(PM.TRAP_INT_MUL_2);

    num_mul_1.multiply(num_mul_2);
    PM.check(PM.TRAP_INT_MUL_3);
    short len = num_mul_1.toByteArray(apdubuf, (short) 0);
    apdu.setOutgoingAndSend((short) 0, len);
}
 
Example #24
Source File: LedgerWalletApplet.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void handleGetHalfPublicKey(APDU apdu) throws ISOException {
 byte[] buffer = apdu.getBuffer();
 apdu.setIncomingAndReceive();
 short offset = ISO7816.OFFSET_CDATA;
 byte derivationSize = buffer[offset++];
 byte i;
 if (Crypto.keyAgreement == null) {
  ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
 }
 if (derivationSize > MAX_DERIVATION_PATH) {
  ISOException.throwIt(ISO7816.SW_DATA_INVALID);
 }
    Crypto.initCipher(chipKey, false);
    Crypto.blobEncryptDecrypt.doFinal(masterDerived, (short)0, (short)DEFAULT_SEED_LENGTH, scratch256, (short)0);
    i = Bip32Cache.copyPrivateBest(buffer, (short)(ISO7816.OFFSET_CDATA + 1), derivationSize, scratch256, (short)0);
    for (; i<derivationSize; i++) {
     Util.arrayCopyNonAtomic(buffer, (short)(offset + 4 * i), scratch256, Bip32.OFFSET_DERIVATION_INDEX, (short)4);
     if ((proprietaryAPI == null) && ((scratch256[Bip32.OFFSET_DERIVATION_INDEX] & (byte)0x80) == 0)) {
      if (!Bip32Cache.setPublicIndex(buffer, (short)(ISO7816.OFFSET_CDATA + 1), i)) {
       ISOException.throwIt(SW_PUBLIC_POINT_NOT_AVAILABLE);
      }
     }
     if (!Bip32.derive(buffer)) {
      ISOException.throwIt(ISO7816.SW_WRONG_DATA);
     }
     Bip32Cache.storePrivate(buffer, (short)(ISO7816.OFFSET_CDATA + 1), (byte)(i + 1), scratch256);
    }
    Crypto.initTransientPrivate(scratch256, (short)0);
    Crypto.keyAgreement.init(Crypto.transientPrivate);
    Crypto.keyAgreement.generateSecret(Secp256k1.SECP256K1_G, (short)0, (short)Secp256k1.SECP256K1_G.length, scratch256, (short)32);
    offset = 0;
    Crypto.random.generateData(buffer, (short)offset, (short)32);
    offset += 32;
    Util.arrayCopyNonAtomic(scratch256, (short)32, buffer, offset, (short)32);
    offset += 32;
    signTransientPrivate(scratch256, (short)0, buffer, (short)0, buffer, offset);
    offset += buffer[(short)(offset + 1)] + 2;
    Crypto.digestScratch.doFinal(buffer, (short)0, (short)32, buffer, (short)0);
    apdu.setOutgoingAndSend((short)0, offset);
}
 
Example #25
Source File: TestTransaction.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public void testTX2ContactlessDisconnectReconnectSwap() throws BTChipException {
	KeycardHelper keycardHelper = new KeycardHelper(DEFAULT_KEYCARD);
	BTChipDongle dongle = prepareDongleRestoreTestnet(true);
	simulator.changeProtocol("T=CL,TYPE_A,T1");
	dongle.verifyPin(DEFAULT_PIN);
	BitcoinTransaction txin_1 = new BitcoinTransaction(new ByteArrayInputStream(TXIN_2_1));
	BitcoinTransaction txin_2 = new BitcoinTransaction(new ByteArrayInputStream(TXIN_2_2));
	BitcoinTransaction txout_1 = new BitcoinTransaction(new ByteArrayInputStream(TXOUT_2));
	BTChipDongle.BTChipInput input1 = dongle.getTrustedInput(txin_1, 1);
	BTChipDongle.BTChipInput input2 = dongle.getTrustedInput(txin_2, 0);
	dongle.startUntrustedTransaction(
		true, 
		0, 
		new BTChipDongle.BTChipInput[] { input1, input2 }, 
		txin_1.getOutputs().get(1).getScript());
	BTChipDongle.BTChipOutput output = dongle.finalizeInputFull(txout_1.serializeOutputs(), "44'/0'/0'/1/0");		
	assertEquals(output.getUserConfirmation(), BTChipDongle.UserConfirmation.KEYCARD);		
	// Keycard validation is done while still in the field
	byte[] keycardIndexes = ((BTChipDongle.BTChipOutputKeycard)output).getKeycardIndexes();
	assertEquals(keycardIndexes.length, DEFAULT_KEYCARD_ADDRESS_SIZE);
	reset();
	// Card is removed from the field		
	// Reinitialize the transient parser
	dongle.startUntrustedTransaction(
		false, 
		0, 
		new BTChipDongle.BTChipInput[] { input2, input1 }, 
		txin_2.getOutputs().get(0).getScript());
	try {
		dongle.finalizeInputFull(txout_1.serializeOutputs(), "44'/0'/0'/1/0");						
		fail();
	}
	catch(BTChipException e) {
		assertEquals(e.getSW(), ISO7816.SW_WRONG_DATA);
	}				
}
 
Example #26
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process an APDU
 *
 * This is the outer layer of our APDU dispatch.
 *
 * It deals with the CLA and INS of the APDU,
 * leaving the rest to an INS-specific function.
 *
 * @param apdu to be processed
 * @throws ISOException on error
 */
public final void process(APDU apdu) throws ISOException {
    byte[] buffer = apdu.getBuffer();
    byte ins = buffer[ISO7816.OFFSET_INS];

    // handle selection of the applet
    if(selectingApplet()) {
        vars[VAR_SELECTED_FILE] = FILEID_NONE;
        return;
    }

    // secure messaging is not supported
    if(apdu.isSecureMessagingCLA()) {
        ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED);
    }

    // process commands to the applet
    if(apdu.isISOInterindustryCLA()) {
        if (ins == INS_SELECT) {
            processSelect(apdu);
        } else if (ins == INS_READ_BINARY) {
            processReadBinary(apdu);
        } else if (ins == INS_UPDATE_BINARY) {
            if(FEATURE_WRITING) {
                processUpdateBinary(apdu);
            } else {
                ISOException.throwIt(ISO7816.SW_COMMAND_NOT_ALLOWED);
            }
        } else {
            ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
        }
    } else {
        ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
    }
}
 
Example #27
Source File: CardProfile.java    From CardExamples with The Unlicense 5 votes vote down vote up
public void setMinThresholdNumberPtpSuk(byte minThresholdNumberPtpSuk) {
    if (minThresholdNumberPtpSuk == (byte) 0) {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }

    this.minThresholdNumberPtpSuk = (int) (minThresholdNumberPtpSuk & 0xFF);
}
 
Example #28
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create and initialize the CAPABILITIES file
 *
 * @param dataSize to be allocated
 * @param dataReadAccess to put in the CC
 * @param dataWriteAccess to put in the CC
 * @return an array for use as the CC file
 */
private byte[] makeCaps(short dataSize,
                        byte dataReadAccess, byte dataWriteAccess) {
    short capsLen = (short)(CC_LEN_HEADER + 2 + CC_LEN_NDEF_FILE_CONTROL);
    byte[] caps = new byte[capsLen];

    short pos = 0;

    // CC length
    pos = Util.setShort(caps, pos, capsLen);
    // mapping version
    caps[pos++] = NDEF_MAPPING_VERSION;
    // maximum read size
    pos = Util.setShort(caps, pos, NDEF_MAX_READ);
    // maximum write size
    pos = Util.setShort(caps, pos, NDEF_MAX_WRITE);

    // NDEF File Control TLV
    caps[pos++] = CC_TAG_NDEF_FILE_CONTROL;
    caps[pos++] = CC_LEN_NDEF_FILE_CONTROL;
    // file ID
    pos = Util.setShort(caps, pos, FILEID_NDEF_DATA);
    // file size
    pos = Util.setShort(caps, pos, dataSize);
    // read access
    caps[pos++] = dataReadAccess;
    // write access
    caps[pos++] = dataWriteAccess;

    // check consistency
    if(pos != capsLen) {
        ISOException.throwIt(ISO7816.SW_UNKNOWN);
    }

    // return the file
    return caps;
}
 
Example #29
Source File: CardEdge.java    From SatochipApplet with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 
 * This function verifies a PIN number sent by the DATA portion. The length of
 * this PIN is specified by the value contained in P3.
 * Multiple consecutive unsuccessful PIN verifications will block the PIN. If a PIN
 * blocks, then an UnblockPIN command can be issued.
 * 
 * ins: 0x42
 * p1: PIN number (0x00-0x07)
 * p2: 0x00
 * data: [PIN] 
 * return: none (throws an exception in case of wrong PIN)
 */
private short VerifyPIN(APDU apdu, byte[] buffer) {
	byte pin_nb = buffer[ISO7816.OFFSET_P1];
	if ((pin_nb < 0) || (pin_nb >= MAX_NUM_PINS))
		ISOException.throwIt(SW_INCORRECT_P1);
	OwnerPIN pin = pins[pin_nb];
	if (pin == null)
		ISOException.throwIt(SW_INCORRECT_P1);
	if (buffer[ISO7816.OFFSET_P2] != 0x00)
		ISOException.throwIt(SW_INCORRECT_P2);
	short bytesLeft = Util.makeShort((byte) 0x00, buffer[ISO7816.OFFSET_LC]);
	/*
	 * Here I suppose the PIN code is small enough to enter in the buffer
	 * TODO: Verify the assumption and eventually adjust code to support
	 * reading PIN in multiple read()s
	 */
	if (!CheckPINPolicy(buffer, ISO7816.OFFSET_CDATA, (byte) bytesLeft))
		ISOException.throwIt(SW_INVALID_PARAMETER);
	byte triesRemaining	= pin.getTriesRemaining();
	if (triesRemaining == (byte) 0x00)
		ISOException.throwIt(SW_IDENTITY_BLOCKED);
	if (!pin.check(buffer, (short) ISO7816.OFFSET_CDATA, (byte) bytesLeft)) {
		LogoutIdentity(pin_nb);
		ISOException.throwIt((short)(SW_PIN_FAILED + triesRemaining - 1));
	}
	
	// Actually register that PIN has been successfully verified.
	logged_ids |= (short) (0x0001 << pin_nb);
	
	return (short)0;
}
 
Example #30
Source File: AccountParamsStatic.java    From CardExamples with The Unlicense 5 votes vote down vote up
public void setMaxNumberAccountParamsDynamic(byte maxNumberAccountParamsDynamic) {
    if (maxNumberAccountParamsDynamic == (byte) 0) {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }

    this.maxNumAcctParamsDynamic = (int) (maxNumberAccountParamsDynamic & 0xFF);
}