javacard.security.DESKey Java Examples

The following examples show how to use javacard.security.DESKey. 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: OpenPGPSecureMessaging.java    From javacard-openpgpcard with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a new secure messaging wrapper.
 */
public OpenPGPSecureMessaging() {
    ssc = JCSystem.makeTransientByteArray(SSC_SIZE, 
            JCSystem.CLEAR_ON_DESELECT);
    tmp = JCSystem.makeTransientByteArray(TMP_SIZE, 
            JCSystem.CLEAR_ON_DESELECT);
    signer = Signature.getInstance(
            Signature.ALG_DES_MAC8_ISO9797_1_M2_ALG3, false);
    verifier = Signature.getInstance(
            Signature.ALG_DES_MAC8_ISO9797_1_M2_ALG3, false);
    cipher = Cipher.getInstance(
            Cipher.ALG_DES_CBC_ISO9797_M2, false);
    decipher = Cipher.getInstance(
            Cipher.ALG_DES_CBC_ISO9797_M2, false);
    
    keyMAC = (DESKey) KeyBuilder.buildKey(
            KeyBuilder.TYPE_DES_TRANSIENT_DESELECT, 
            KeyBuilder.LENGTH_DES3_2KEY, false);
    keyENC = (DESKey) KeyBuilder.buildKey(
            KeyBuilder.TYPE_DES_TRANSIENT_DESELECT, 
            KeyBuilder.LENGTH_DES3_2KEY, false);
    
    ssc_set = JCSystem.makeTransientBooleanArray((short)1, JCSystem.CLEAR_ON_DESELECT);
    ssc_set[0] = false;
}
 
Example #2
Source File: PinTests.java    From GidsApplet with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void authenticateGeneralReplayAttack() {
    byte[] challenge, challengeresponse = new byte[8];
    byte[] key = DatatypeConverter.parseHexBinary("010203040506070801020304050607080102030405060708");
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);

    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 04 7C 02 81 00 00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x0A,(byte) 0x81,0x08})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    challenge = Arrays.copyOfRange(response.getBytes(), 4, 12);
    //solve challenge
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(challenge, (short) 0, (short)8, challengeresponse, (short) 0);
    // send the response
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), 0x9000);
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), 0x6985);
}
 
Example #3
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 6 votes vote down vote up
protected void authenticateGeneral(byte[] key, boolean successexpected) {
    byte[] challenge, challengeresponse = new byte[8];
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);

    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 04 7C 02 81 00 00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x0A,(byte) 0x81,0x08})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    challenge = Arrays.copyOfRange(response.getBytes(), 4, 12);
    //solve challenge
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(challenge, (short) 0, (short)8, challengeresponse, (short) 0);
    // send the response
    execute("00 87 00 00 0C 7C 0A 82 08" + DatatypeConverter.printHexBinary(challengeresponse), (successexpected?0x9000: 0x6982));
}
 
Example #4
Source File: Keycard.java    From ledger-javacard with GNU Affero General Public License v3.0 6 votes vote down vote up
public static boolean check(byte[] address, short addressOffset, byte addressSize, byte[] code, short codeOffset, byte codeSize, byte[] indexes, short indexesOffset, byte[] scratch, short scratchOffset) {
    byte size = (userKeycardSize != (byte)0 ? userKeycardSize : issuerKeycardSize);                
    DESKey key = (userKeycardSize != (byte)0 ? userKeycard : issuerKeycard);
    byte i;
    for (i=0; i<KEYCARD_SIZE; i++) {
        scratch[(short)(scratchOffset + i)] = i;
    }
    Crypto.initCipher(key, true);
    Crypto.blobEncryptDecrypt.doFinal(scratch, scratchOffset, KEYCARD_SIZE, scratch, scratchOffset);
    for (i=0; i<KEYCARD_SIZE; i++) {
        scratch[(short)(scratchOffset + i)] = (byte)(((scratch[(short)(scratchOffset + i)] >> 4) & 0x0f) ^ (scratch[(short)(scratchOffset + i)] & 0x0f));
    }
    for (i=0; i<size; i++) {
        short addressCode;
        if (address != null) {
            addressCode = (short)((address[(short)(addressOffset + indexes[(short)(indexesOffset + i)])] & 0xff) - (short)0x30);
        }
        else {
            addressCode = indexes[(short)(indexesOffset + i)];
        }
        if (code[(short)(codeOffset + i)] != scratch[(short)(scratchOffset + addressCode)]) {
            return false;
        }
    }
    return true;
}
 
Example #5
Source File: PinTests.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void authenticateMutualReplayAttack() {
    byte[] key = DatatypeConverter.parseHexBinary("010203040506070801020304050607080102030405060708");
    byte[] myChallenge= new byte [16], globalchallenge = new byte[40], challengeresponse = new byte[40];
    byte[] challenge;
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);
    RandomData randomData = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
    randomData.generateData(myChallenge, (short) 0, (short) myChallenge.length);
    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 14 7C 12 81 10" + DatatypeConverter.printHexBinary(myChallenge) + "00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x12,(byte) 0x81,0x10})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    challenge = Arrays.copyOfRange(response.getBytes(), 4, 20);
    //solve challenge
    //R2
    System.arraycopy(challenge, 0, globalchallenge, 0, 16);
    //R1
    System.arraycopy(myChallenge, 0, globalchallenge, 16, 16);
    // keep Z1 random
    globalchallenge[(short)39] = (byte) 0x80;
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(globalchallenge, (short) 0, (short)40, challengeresponse, (short) 0);
    // send the response
    execute("00 87 00 00 2C 7C 2A 82 28" + DatatypeConverter.printHexBinary(challengeresponse), 0x9000);
    execute("00 87 00 00 2C 7C 2A 82 28" + DatatypeConverter.printHexBinary(challengeresponse), 0x6985);
}
 
Example #6
Source File: LedgerWalletApplet.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public LedgerWalletApplet(byte[] parameters, short parametersOffset, byte parametersLength) {
    BCDUtils.init();
    TC.init();
    Crypto.init();
    Transaction.init();
    Bip32Cache.init();
    Keycard.init();
    limits = new byte[LIMIT_LAST];
    scratch256 = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
    transactionPin = new OwnerPIN(TRANSACTION_PIN_ATTEMPTS, TRANSACTION_PIN_SIZE);
    walletPin = new OwnerPIN(WALLET_PIN_ATTEMPTS, WALLET_PIN_SIZE);
    secondaryPin = new OwnerPIN(SECONDARY_PIN_ATTEMPTS, SECONDARY_PIN_SIZE);
    masterDerived = new byte[64];
    chipKey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    trustedInputKey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    developerKey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    try {
        pairingKey = (AESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_256, false);
    }
    catch(Exception e) {
    }
    reset();
    if (parametersLength != 0) {
        attestationPrivate = (ECPrivateKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false);
        attestationPublic = new byte[65];
        Secp256k1.setCommonCurveParameters(attestationPrivate);
        attestationPrivate.setS(parameters, parametersOffset, (short)32);
        parametersOffset += (short)32;
        attestationSignature = new byte[parameters[(short)(parametersOffset + 1)] + 2];
        Util.arrayCopy(parameters, parametersOffset, attestationSignature, (short)0, (short)attestationSignature.length);
    }
}
 
Example #7
Source File: STPayW.java    From CardExamples with The Unlicense 5 votes vote down vote up
/**
 * Creates Java Card applet object.
 * 
 * @param array
 *            the byte array containing the AID bytes
 * @param offset
 *            the start of AID bytes in array
 * @param length
 *            the length of the AID bytes in array
 */
private STPayW(byte[] array, short offset, byte length) {
    this.udk = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);

    this.udkMsd = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);

    this.tempKey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES_TRANSIENT_DESELECT, KeyBuilder.LENGTH_DES3_2KEY, false);

    this.gpState = GPSystem.APPLICATION_SELECTABLE;

    this.accountParamsStatic = new AccountParamsStatic();

    // Build Static Account Parameters.
    // NOTE: This is a kludge to retrieve AID. This would not work with real Java Card.
    byte[] aidBuffer = new byte[16];
    byte aidLength = JCSystem.getAID().getBytes(aidBuffer, (short) 0);
    this.accountParamsStatic.setAid(aidBuffer, (short) 0, aidLength);

    this.sequenceCounter = (short) 0;

    try {
        setStatePerso();
    }
    catch (IOException e) {
    }

    // Register instance AID.
    register(array, (short) (offset + (byte) 1), array[offset]);
}
 
Example #8
Source File: GidsBaseTestClass.java    From GidsApplet with GNU General Public License v3.0 4 votes vote down vote up
protected void authenticateMutual(byte[] key, boolean successexpected) {
    byte[] myChallenge= new byte [16], globalchallenge = new byte[40], challengeresponse = new byte[40];
    byte[] cardChallenge;
    Cipher cipherDES = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    DESKey deskey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_3KEY, false);
    deskey.setKey(key, (short) 0);
    new Random().nextBytes(myChallenge);
    // select admin key
    execute("00 22 81 A4 03 83 01 80");
    // get a challenge
    ResponseAPDU response = execute("00 87 00 00 14 7C 12 81 10" + DatatypeConverter.printHexBinary(myChallenge) + "00");
    if (!Arrays.equals(Arrays.copyOfRange(response.getBytes(), 0, 4), new byte[] {0x7C,0x12,(byte) 0x81,0x10})) {
        fail("not a challenge:" + DatatypeConverter.printHexBinary(response.getBytes()));
    }
    // compute the response
    cardChallenge = Arrays.copyOfRange(response.getBytes(), 4, 20);
    //solve challenge
    //R2
    System.arraycopy(cardChallenge, 0, globalchallenge, 0, 16);
    //R1
    System.arraycopy(myChallenge, 0, globalchallenge, 16, 16);
    // keep Z1 random
    globalchallenge[(short)39] = (byte) 0x80;
    cipherDES.init(deskey, Cipher.MODE_ENCRYPT);
    cipherDES.doFinal(globalchallenge, (short) 0, (short)40, challengeresponse, (short) 0);
    // send the response
    String command = "00 87 00 00 2C 7C 2A 82 28" + DatatypeConverter.printHexBinary(challengeresponse);
    
    ResponseAPDU responseAPDU = execute(command, true);
    
    if (!successexpected)
    {
        if(responseAPDU.getSW() != 0x6982) {
            fail("expected: " + Integer.toHexString(0x6982) + " but was: " + Integer.toHexString(response.getSW()));
        }
        return;
    }
    if(responseAPDU.getSW() != 0x9000) {
        fail("expected: " + Integer.toHexString(0x9000) + " but was: " + Integer.toHexString(response.getSW()));
    }
    byte[] cardresponse = responseAPDU.getBytes();
    if (!Arrays.equals(Arrays.copyOfRange(cardresponse, 0, 4), new byte[] {0x7C,0x2A,(byte)0x82,0x28}))
    {
        fail("header verification failed");
    }
    byte[] decryptedCardResponse = new byte[40];
    cipherDES.init(deskey, Cipher.MODE_DECRYPT);
    cipherDES.doFinal(cardresponse, (short) 4, (short)40, decryptedCardResponse, (short) 0);
   
    
    if (!Arrays.equals(Arrays.copyOfRange(decryptedCardResponse, 0, 16), myChallenge)) {
        fail("R1 verification failed");
    }
    
    if (!Arrays.equals(Arrays.copyOfRange(decryptedCardResponse, 16, 32), cardChallenge)) {
        fail("R2 verification failed");
    }
    if (decryptedCardResponse[(short)39] != (byte) 0x80) {
        fail("padding failed");
    }
    
}
 
Example #9
Source File: Keycard.java    From ledger-javacard with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void init() {
    issuerKeycard = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    userKeycard = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    pairingData = JCSystem.makeTransientByteArray((byte)(PAIRING_DATA_SIZE + 1), JCSystem.CLEAR_ON_DESELECT);
    challenge = JCSystem.makeTransientByteArray((byte)4, JCSystem.CLEAR_ON_DESELECT);
}
 
Example #10
Source File: Crypto.java    From ledger-javacard with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void initCipher(DESKey key, boolean encrypt) {
    blobEncryptDecrypt.init(key, (encrypt ? Cipher.MODE_ENCRYPT : Cipher.MODE_DECRYPT), IV_ZERO, (short)0, (short)IV_ZERO.length);
}
 
Example #11
Source File: STPayP.java    From CardExamples with The Unlicense 4 votes vote down vote up
/**
 * Creates Java Card applet object.
 * 
 * @param array
 *            the byte array containing the AID bytes
 * @param offset
 *            the start of AID bytes in array
 * @param length
 *            the length of the AID bytes in array
 */
private STPayP(byte[] array, short offset, byte length) {
    /*** Start allocate memory when applet is instantiated. ***/
    this.records = new Records(Constants.MAX_SFI_RECORDS);

    this.persistentByteBuffer = new byte[Constants.SIZE_PBB];
    this.personalizedPersistentByteBuffer = new byte[Constants.SIZE_PPBB];

    this.transientByteBuffer = JCSystem.makeTransientByteArray(Constants.SIZE_TBB, JCSystem.CLEAR_ON_DESELECT);

    // NOTE: 'keyEncryption' parameter not used.
    this.mkAC = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    this.mkIDN = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false);
    /*** End allocate memory when applet is instantiated. ***/

    /*** Allocate memory when personalized. ***/
    this.selectResponse = null;
    this.cardLayoutDescriptionPart1 = null;
    this.cardLayoutDescriptionPart2 = null;
    this.cardLayoutDescriptionPart3 = null;

    this.gpState = GPSystem.APPLICATION_SELECTABLE;

    /*** Start initialize variables specific to MPP Remote-SE Lite. ***/
    this.cardProfile = new CardProfile();

    // Build Card Profile.
    // NOTE: This is a kludge to retrieve AID. This would not work with real Java Card.
    byte aidLength = JCSystem.getAID().getBytes(this.transientByteBuffer, (short) 0);
    this.cardProfile.setAid(this.transientByteBuffer, (short) 0, aidLength);

    this.cardProfileHash = new byte[32];

    // Initialize and seed random.
    this.random = RandomData.getInstance(RandomData.ALG_PSEUDO_RANDOM);
    byte[] seed = DataUtil.stringToCompressedByteArray(String.valueOf(Calendar.getInstance().getTimeInMillis()));
    this.random.setSeed(seed, (short) 0, (short) seed.length);

    // Initialize Mobile Key.
    this.dataEncryption = new DataEncryption();
    if (!this.dataEncryption.initMobileKey()) {
        System.out.println("Error: M_Key not initialized.");
    }

    this.sha256 = MessageDigest.getInstance(MessageDigest.ALG_SHA_256, false);
    /*** End initialize variables specific to MPP Remote-SE Lite. ***/

    // Register instance AID.
    register(array, (short) (offset + (byte) 1), array[offset]);
}
 
Example #12
Source File: PayPass.java    From CardExamples with The Unlicense 4 votes vote down vote up
public PayPass(byte[] bArray, short bOffset, byte bLength) {
    if (bLength != 27)
        ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    // transaction starts
    JCSystem.beginTransaction();

    // set up and initialize all the DES encryption/descrytion ciphers used in the app
    DESKEY_KD_PERSO_L_EN = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    DESKEY_KD_PERSO_R_DE = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    DESKEY_KD_PERSO_L_DE = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    DESKEY_KD_PERSO_R_EN = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    CIPHER_KD_PERSO_L_EN = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false);
    CIPHER_KD_PERSO_R_DE = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false);
    CIPHER_KD_PERSO_L_DE = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false);
    CIPHER_KD_PERSO_R_EN = Cipher.getInstance(Cipher.ALG_DES_ECB_NOPAD, false);

    // transaction ends
    JCSystem.commitTransaction();

    // define RAM buffers for faster operation
    CVC3_DATA = JCSystem.makeTransientByteArray((short) 16, JCSystem.CLEAR_ON_DESELECT);
    CMD_BUF = JCSystem.makeTransientByteArray((short) 261, JCSystem.CLEAR_ON_DESELECT);
    MAC = JCSystem.makeTransientByteArray((short) 8, JCSystem.CLEAR_ON_DESELECT);

    // on initialize the current state is not_alive
    state = not_alive;

    PROFILE = new Profile();

    // testing area
    // pre-personalization data
    // issuer supply
    PROFILE.VER_KMC = (byte) 0x01;  // MC version
    PROFILE.VER_KMC = bArray[bOffset];  // MC version
    PROFILE.KMC_ID[0] = (byte) 0x54;  // key id
    PROFILE.KMC_ID[1] = (byte) 0x13;
    PROFILE.KMC_ID[2] = (byte) 0x12;
    PROFILE.KMC_ID[3] = (byte) 0xFF;
    PROFILE.KMC_ID[4] = (byte) 0xFF;
    PROFILE.KMC_ID[5] = (byte) 0xFF;
    Util.arrayCopyNonAtomic(bArray, (short) (bOffset + 1), PROFILE.KMC_ID, (short) 0, (short) 6);
    PROFILE.KD_PERSO[0] = (byte) 0xA8;  // personalization key
    PROFILE.KD_PERSO[1] = (byte) 0x6A;
    PROFILE.KD_PERSO[2] = (byte) 0x3D;
    PROFILE.KD_PERSO[3] = (byte) 0x06;
    PROFILE.KD_PERSO[4] = (byte) 0xCA;
    PROFILE.KD_PERSO[5] = (byte) 0xE7;
    PROFILE.KD_PERSO[6] = (byte) 0x04;
    PROFILE.KD_PERSO[7] = (byte) 0x6A;
    PROFILE.KD_PERSO[8] = (byte) 0x10;
    PROFILE.KD_PERSO[9] = (byte) 0x63;
    PROFILE.KD_PERSO[10] = (byte) 0x58;
    PROFILE.KD_PERSO[11] = (byte) 0xD5;
    PROFILE.KD_PERSO[12] = (byte) 0xB8;
    PROFILE.KD_PERSO[13] = (byte) 0x23;
    PROFILE.KD_PERSO[14] = (byte) 0x9C;
    PROFILE.KD_PERSO[15] = (byte) 0xBE;
    Util.arrayCopyNonAtomic(bArray, (short) (bOffset + 7), PROFILE.KD_PERSO, (short) 0, (short) 16);
    PROFILE.CSN[0] = (byte) 0x89;
    PROFILE.CSN[1] = (byte) 0xAA;
    PROFILE.CSN[2] = (byte) 0x7F;
    PROFILE.CSN[3] = (byte) 0x00;
    Util.arrayCopyNonAtomic(bArray, (short) (bOffset + 23), PROFILE.CSN, (short) 0, (short) 4);
    // end issuer supply

    // profile can now be considered in personalization state
    PROFILE.STATE = PERSO;
}