javacard.framework.JCSystem Java Examples

The following examples show how to use javacard.framework.JCSystem. 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: ObjectAllocator.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
 * All type of allocator for selected object as RAM (faster), rest EEPROM (saving RAM)
 * The current settings is heuristically obtained from measurements of performance of Bignat and ECPoint operations 
 */    
public void setAllocatorsTradeoff() {
    // Set initial allocators into EEPROM
    setAllAllocatorsEEPROM();
    
    // Put only the most perfromance relevant ones into RAM
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_array1] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_array2] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_A] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_B] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_C] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_D] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_E] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[BNH_helper_BN_F] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[ECPH_helperEC_BN_B] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[ECPH_helperEC_BN_C] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
    ALLOCATOR_TYPE_ARRAY[ECPH_uncompressed_point_arr1] = JCSystem.MEMORY_TYPE_TRANSIENT_RESET;
}
 
Example #3
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 #4
Source File: Crypto.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
Crypto() {
  random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
  sha256 = MessageDigest.getInstance(MessageDigest.ALG_SHA_256, false);
  ecdh = KeyAgreement.getInstance(KeyAgreement.ALG_EC_SVDP_DH_PLAIN, false);
  sha512 = MessageDigest.getInstance(MessageDigest.ALG_SHA_512, false);
  aesCbcIso9797m2 = Cipher.getInstance(Cipher.ALG_AES_CBC_ISO9797_M2,false);

  try {
    hmacSHA512 = Signature.getInstance(Signature.ALG_HMAC_SHA_512, false);
    hmacKey = (HMACKey) KeyBuilder.buildKey(KeyBuilder.TYPE_HMAC_TRANSIENT_DESELECT, KeyBuilder.LENGTH_AES_256, false);
  } catch (CryptoException e) {
    hmacSHA512 = null;
    hmacBlock = JCSystem.makeTransientByteArray(HMAC_BLOCK_SIZE, JCSystem.CLEAR_ON_RESET);
  }

}
 
Example #5
Source File: BerTlvFile.java    From GidsApplet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * \brief Delete a DO
 *
 * This method requests garbage collection.
 *
 * \param childNum internal index
 */
protected void deleteChildren(short childNum) {

    // Fill up empty field in children array.
    if(!JCSystem.isObjectDeletionSupported()) {
        children[childNum].clearContents();
    }

    children[childNum] = null;
    currentNumChildren--; // We have one less children now.


    // The last children is one ahead, so it is at currentNumChildren.
    if(childNum < currentNumChildren) {
        children[childNum] = children[currentNumChildren];
    }

    // Clean up the old file object.
    if(JCSystem.isObjectDeletionSupported()) {
        JCSystem.requestObjectDeletion();
    }
}
 
Example #6
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Main constructor
 *
 * This will construct and initialize an instance
 * of this applet according to the provided app data.
 *
 * @param buf containing application data
 * @param off offset of app data in buf
 * @param len length of app data in buf
 */
protected NdefApplet(byte[] buf, short off, byte len) {
    // length of actual data file
    short dataLen = (short)(len + 2);
    // create transient variables
    vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT);
    // create capabilities files
    capsFile = makeCaps(dataLen);
    // create data file
    byte[] data = null;
    if (len > 0) {
        data = new byte[dataLen];
        // container size
        Util.setShort(data, (short) 0, len);
        // initial data
        Util.arrayCopyNonAtomic(buf, off, data, (short) 2, len);
    } else {
        ISOException.throwIt(ISO7816.SW_DATA_INVALID);
    }
    dataFile = data;
}
 
Example #7
Source File: OCUnitTests.java    From JCMathLib with MIT License 6 votes vote down vote up
void test_EC_SETCURVE_G(APDU apdu, short dataLen) {
     byte[] apdubuf = apdu.getBuffer();
     
     Util.arrayCopyNonAtomic(apdubuf, ISO7816.OFFSET_CDATA, m_customG, (short) 0, dataLen);
     PM.check(PM.TRAP_EC_SETCURVE_1);

     if (apdubuf[ISO7816.OFFSET_P2] == 1) { // If required, complete new custom curve and point is allocated
         m_testCurveCustom = new ECCurve(false, SecP256r1.p, SecP256r1.a, SecP256r1.b, m_customG, SecP256r1.r);
         m_testPointCustom = new ECPoint(m_testCurveCustom, m_ecc.ech);
         PM.check(PM.TRAP_EC_SETCURVE_2);
         // Release unused previous objects
         if (!bIsSimulator) {
             JCSystem.requestObjectDeletion();
         }
     }
     else {
         // Otherwise, only G is set and relevant objects are updated
         m_testCurveCustom.setG(apdubuf, (short) ISO7816.OFFSET_CDATA, m_testCurveCustom.POINT_SIZE);
         m_testPointCustom.updatePointObjects(); // After changing curve parameters, internal objects needs to be actualized
     }
}
 
Example #8
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Main constructor
 *
 * This will construct and initialize an instance
 * of this applet according to the provided app data.
 *
 * @param buf containing application data
 * @param off offset of app data in buf
 * @param len length of app data in buf
 */
protected NdefApplet(byte[] buf, short off, byte len) {
    // create transient variables
    vars = JCSystem.makeTransientShortArray(NUM_VARS, JCSystem.CLEAR_ON_DESELECT);
    refs = JCSystem.makeTransientObjectArray(NUM_REFS, JCSystem.CLEAR_ON_DESELECT);
    // create capabilities files
    capsFile = makeCaps((short)0);
    // process install data
    if(len < 6 || len > 17) {
        ISOException.throwIt(ISO7816.SW_WRONG_DATA);
    }
    // first byte is the service ID
    serviceID = buf[off++]; len--;
    // rest is the service AID
    serviceAID = new byte[len];
    Util.arrayCopyNonAtomic(buf, off, serviceAID, (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
/**
 * 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 #10
Source File: FIDOStandalone.java    From ledger-u2f-javacard with Apache License 2.0 6 votes vote down vote up
/**
 * Init cipher engines and allocate memory.
 */
public FIDOStandalone() {
    scratch = JCSystem.makeTransientByteArray((short) 64, JCSystem.CLEAR_ON_DESELECT);
    keyPair = new KeyPair(
    (ECPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false),
    (ECPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false));
    Secp256r1.setCommonCurveParameters((ECKey) keyPair.getPrivate());
    Secp256r1.setCommonCurveParameters((ECKey) keyPair.getPublic());
    random = RandomData.getInstance(RandomData.ALG_KEYGENERATION);
    // Initialize the unique wrapping key
    chipKey = (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_256, false);
    random.nextBytes(scratch, (short) 0, (short) 32);
    chipKey.setKey(scratch, (short) 0);
    cipherEncrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
    cipherEncrypt.init(chipKey, Cipher.MODE_ENCRYPT, IV_ZERO_AES, (short) 0, (short) IV_ZERO_AES.length);
    cipherDecrypt = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
    cipherDecrypt.init(chipKey, Cipher.MODE_DECRYPT, IV_ZERO_AES, (short) 0, (short) IV_ZERO_AES.length);
}
 
Example #11
Source File: SHA512.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public SHA512() {
  working = JCSystem.makeTransientShortArray((short)(2 + 8*4
                                                       ),
                                               JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT);
  blk = JCSystem.makeTransientShortArray((short)(64),
                                               JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT);
  init();
}
 
Example #12
Source File: GidsPINManager.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
public GidsPINManager() {
    pin_pin = new GidsPIN(PIN_MAX_TRIES, PIN_MAX_LENGTH, PIN_MIN_LENGTH);
    ExternalChallenge = JCSystem.makeTransientByteArray((short)16, JCSystem.CLEAR_ON_DESELECT);
    CardChallenge = JCSystem.makeTransientByteArray((short)16, JCSystem.CLEAR_ON_DESELECT);
    KeyReference = JCSystem.makeTransientObjectArray((short)1, JCSystem.CLEAR_ON_DESELECT);
    buffer = JCSystem.makeTransientByteArray((short)40, JCSystem.CLEAR_ON_DESELECT);
    sharedKey = JCSystem.makeTransientByteArray((short)40, JCSystem.CLEAR_ON_DESELECT);
    status = JCSystem.makeTransientByteArray((short)1, JCSystem.CLEAR_ON_DESELECT);
}
 
Example #13
Source File: FIDOCCImplementation.java    From CCU2F with Apache License 2.0 5 votes vote down vote up
private short computeHmacSha256(byte[] key, short key_offset, short key_length, 
	byte[] message, short message_offset, short message_length,
	byte[] mac, short mac_offset){
  	
  	byte[] hmacBuffer = JCSystem.makeTransientByteArray((short) 128, JCSystem.CLEAR_ON_DESELECT);

  	short BLOCKSIZE=64; 
  	short HASHSIZE=32;
  	
// compute inner hash
for (short i=0; i<key_length; i++){
	hmacBuffer[i]= (byte) (key[(short)(key_offset+i)] ^ (0x36));
}
Util.arrayFillNonAtomic(hmacBuffer, key_length, (short)(BLOCKSIZE-key_length), (byte)0);		
Util.arrayCopyNonAtomic(message, message_offset, hmacBuffer, BLOCKSIZE, message_length);
sha256.reset();
sha256.doFinal(hmacBuffer, (short)0, (short)(BLOCKSIZE+message_length), hmacBuffer, BLOCKSIZE); // copy hash result to data buffer!

// compute outer hash
for (short i=0; i<key_length; i++){
	hmacBuffer[i]= (byte) (key[(short)(key_offset+i)] ^ (0x5c));
}
Util.arrayFillNonAtomic(hmacBuffer, key_length, (short)(BLOCKSIZE-key_length), (byte)0);
// previous hash already copied to correct offset in scratch
sha256.reset();
sha256.doFinal(hmacBuffer, (short)0, (short)(BLOCKSIZE+HASHSIZE), mac, mac_offset);

return HASHSIZE;
  }
 
Example #14
Source File: Bip32Cache.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void init() {
	cache = new Bip32Cache[CACHE_SIZE];
	for (short i=0; i<CACHE_SIZE; i++) {
		cache[i] = new Bip32Cache();
	}
	lastCacheIndex = JCSystem.makeTransientByteArray((short)1, JCSystem.CLEAR_ON_DESELECT);
}
 
Example #15
Source File: TransmitManager.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
public void ClearFlashBuffer() {
    if (flash_buf != null)
    {
        if(JCSystem.isObjectDeletionSupported()) {
            flash_buf = null;
            JCSystem.requestObjectDeletion();
        } else {
            Util.arrayFillNonAtomic(flash_buf, (short)0, FLASH_BUF_SIZE, (byte)0x00);
        }
    }
}
 
Example #16
Source File: LWNFCForumApplet.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public LWNFCForumApplet() {
    scratch = JCSystem.makeTransientByteArray((short)1, JCSystem.CLEAR_ON_DESELECT);
    FILE_DATA = new byte[500];
    // Header initialization
    short offset = 0;
    offset += (short)2;       
    FILE_DATA[offset++] = (byte)0xC1; // beginning of well known record, short record bit not set
    FILE_DATA[offset++] = (byte)0x01;
    FILE_DATA[offset++] = (byte)0x00; // start of 4 bytes length
    FILE_DATA[offset++] = (byte)0x00;
    offset += (short)2;
    Util.arrayCopyNonAtomic(LANG, (short)0, FILE_DATA, offset, (short)LANG.length);                        
    LedgerWalletApplet.writeIdleText();
    created = true;
}
 
Example #17
Source File: CRTKeyFile.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
void clearContents() {
    if (symmetricKey != null) {
        symmetricKey = null;
    }
    if (keyPair != null) {
        keyPair.getPrivate().clearKey();
        keyPair = null;
    }
    if(JCSystem.isObjectDeletionSupported()) {
        JCSystem.requestObjectDeletion();
    }
}
 
Example #18
Source File: FIDOCCImplementation.java    From CCU2F with Apache License 2.0 5 votes vote down vote up
public FIDOCCImplementation() {
	
	random = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
	
    scratch = JCSystem.makeTransientByteArray((short)128, JCSystem.CLEAR_ON_DESELECT);
    //seed = new byte[64];
    
    keyPair = new KeyPair(
        (ECPublicKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PUBLIC, KeyBuilder.LENGTH_EC_FP_256, false),
        (ECPrivateKey)KeyBuilder.buildKey(KeyBuilder.TYPE_EC_FP_PRIVATE, KeyBuilder.LENGTH_EC_FP_256, false));
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPrivate());
    Secp256r1.setCommonCurveParameters((ECKey)keyPair.getPublic());
            
    // Initialize the unique seed for DRNG function 
    //random.generateData(seed, (short)0, (short)64);
    
    // Initialize the unique seed for DRNG function       
    drngSeed1 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_256, false);
    drngSeed2 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_256, false);
    random.generateData(scratch, (short)0, (short)32);
    drngSeed1.setKey(scratch, (short)0);
    random.generateData(scratch, (short)0, (short)32);
    drngSeed2.setKey(scratch, (short)0);
 
    sha256 = MessageDigest.getInstance(MessageDigest.ALG_SHA_256, false);
            
    // Initialize the unique keys for MAC function
    macKey1 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_128, false);
    macKey2 = (AESKey)KeyBuilderX.buildKey(KeyBuilderX.TYPE_AES_STATIC, KeyBuilder.LENGTH_AES_128, false);
    random.generateData(scratch, (short)0, (short)16);
    macKey1.setKey(scratch, (short)0);
    random.generateData(scratch, (short)0, (short)16);
    macKey2.setKey(scratch, (short)0);
    
    // Initialize ecMultiplier 
    ecMultiplyHelper = KeyAgreementX.getInstance(KeyAgreementX.ALG_EC_SVDP_DH_PLAIN_XY, false);
}
 
Example #19
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 #20
Source File: PasswordManagerApplet.java    From sim-password-manager with Apache License 2.0 5 votes vote down vote up
private void generateKeys(APDU apdu) {
    if (keysGenerated) {
        ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
    }

    try {
        JCSystem.beginTransaction();
        prng(keyBytes, OFFSET_ZERO, KEY_LENGTH);
        keysGenerated = true;
    } finally {
        JCSystem.commitTransaction();
    }
}
 
Example #21
Source File: ObjectAllocator.java    From JCMathLib with MIT License 5 votes vote down vote up
/**
 * Allocates new byte[] array with provided length either in RAM or EEPROM based on an allocator type.
 * Method updates internal counters of bytes allocated with specific allocator. Use {@code getAllocatedInRAM()} 
 * or {@code getAllocatedInEEPROM} for counters readout.
 * @param length    length of array
 * @param allocatorType type of allocator
 * @return allocated array 
 */
public byte[] allocateByteArray(short length, byte allocatorType) {
    switch (allocatorType) {
        case JCSystem.MEMORY_TYPE_PERSISTENT:
            allocatedInEEPROM += length;
            return new byte[length];
        case JCSystem.MEMORY_TYPE_TRANSIENT_RESET:
            allocatedInRAM += length;
            return JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_RESET);
        case JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT:
            allocatedInRAM += length;
            return JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT);
    }
    return null;
}
 
Example #22
Source File: Gpg.java    From OpenPGP-Card with GNU General Public License v3.0 5 votes vote down vote up
private void computeSignature(APDU apdu) {
  byte[] buffer = apdu.getBuffer();
  short length = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);
  // Make sure that DigestInfo is <= 40% of the RSA key length.
  if ((short) (length * 4) > (short) (RSA_KEY_LENGTH_BYTES * 10) ||
      apdu.setIncomingAndReceive() != length) {
    ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
  }
  if (!pinSubmitted[PIN_INDEX_PW1] || !pins[PIN_INDEX_PW1].isValidated()) {
    ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
  }
  if (!signatureKey.getPrivate().isInitialized()) {
    ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
  }
  if (pinValidForMultipleSignatures == (byte) 0) {
    pinSubmitted[PIN_INDEX_PW1] = false;
  }

  cipherRSA.init(signatureKey.getPrivate(), Cipher.MODE_ENCRYPT);
  cipherRSA.doFinal(buffer, ISO7816.OFFSET_CDATA, length, buffer, (short) 0);
  JCSystem.beginTransaction();
  if (signatureCounter[2] != (byte) 0xFF) {
    signatureCounter[2] = (byte) ((signatureCounter[2] & 0xFF) + 1);
  } else {
    signatureCounter[2] = 0;
    if (signatureCounter[1] != (byte) 0xFF) {
      signatureCounter[1] = (byte) ((signatureCounter[1] & 0xFF) + 1);
    } else if (signatureCounter[0] != (byte) 0xFF) {
      signatureCounter[1] = 0;
      signatureCounter[0] = (byte) ((signatureCounter[0] & 0xFF) + 1);
    } else {
      JCSystem.abortTransaction();
      ISOException.throwIt(ISO7816.SW_FILE_FULL);
    }
  }
  JCSystem.commitTransaction();
  apdu.setOutgoingAndSend((short) 0, RSA_KEY_LENGTH_BYTES);
}
 
Example #23
Source File: PasswordManagerApplet.java    From sim-password-manager with Apache License 2.0 5 votes vote down vote up
private void clear(APDU apdu) {
    try {
        JCSystem.beginTransaction();
        for (short i = 0; i < KEY_LENGTH; i++) {
            keyBytes[i] = 0;
        }

        keysGenerated = false;
        prngCounter = 0;
    } finally {
        JCSystem.commitTransaction();
    }
}
 
Example #24
Source File: ObjectLocker.java    From JCMathLib with MIT License 5 votes vote down vote up
private final void initialize(short numObjects, boolean bEraseOnLock, boolean bEraseOnUnlock) {
    lockedObjects = JCSystem.makeTransientObjectArray((short) (2 * numObjects), JCSystem.CLEAR_ON_RESET);
    lockedObjectsPersistent = new Object[(short) (2 * numObjects)];
    ERASE_ON_LOCK = bEraseOnLock;
    ERASE_ON_UNLOCK = bEraseOnUnlock;
    profileLockedObjects = new byte[(short) (numObjects * numObjects)]; 
    resetProfileLocks();
}
 
Example #25
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 #26
Source File: JavaCardAES.java    From sim-password-manager with Apache License 2.0 5 votes vote down vote up
public JavaCardAES() {
      // ALLOCATE AND COMPUTE LOOKUP TABLES
      SBox = new byte[256];
      SiBox = new byte[256];
      Alogtable = new byte[256];
// ALOG_MUL     Alogtable_mul2 = new byte[256];
// ALOG_MUL     Alogtable_mul3 = new byte[256];
// ALOG_MUL     Alogtable_mul2 = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_RESET);
// ALOG_MUL     Alogtable_mul3 = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_RESET);
      Logtable = new short[256];
      tempBuffer = JCSystem.makeTransientByteArray(STATELEN, JCSystem.CLEAR_ON_RESET);
      MakeSBox();
    }
 
Example #27
Source File: TC.java    From ledger-javacard with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void init() {
    ctx = JCSystem.makeTransientByteArray(TX_CONTEXT_SIZE, JCSystem.CLEAR_ON_DESELECT);
    ctxP = new byte[P_TX_CONTEXT_SIZE];
}
 
Example #28
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;
}
 
Example #29
Source File: BCDUtils.java    From ledger-javacard with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void init() {
    scratch = JCSystem.makeTransientShortArray((short)(8 * 8 / 3), JCSystem.CLEAR_ON_DESELECT);
}
 
Example #30
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);
}