javacard.framework.Util Java Examples

The following examples show how to use javacard.framework.Util. 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: 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 #2
Source File: Bip32ObjectManager.java    From SatochipApplet with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Creates an object by reserving a fixed memory size for it.
 * Throws a SW_NO_MEMORY_LEFT exception if cannot allocate the memory.
 * 
 * @param src
 *            the source array to copy from
 * @param srcOff
 *            the offset for the source array
 *            
 * @return The memory base address for the object.
 */
public short createObject(byte[] src, short srcOff) {
	if (nb_elem_free == 0)
		ISOException.throwIt(SW_NO_MEMORY_LEFT);		
	
	short base=0;
	while (base<this.size) {
		if (Util.arrayCompare(this.ptr, base, this.empty, (short)0, this.size_id)==0){
			Util.arrayCopyNonAtomic(src, srcOff, this.ptr, base, this.size_elem);
			this.nb_elem_free--;
			this.nb_elem_used++;
			return base;
		}
		base+=this.size_elem;	
	}
	return NULL_OFFSET;//should not happen
}
 
Example #3
Source File: ECPoint.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
 * Compares this and provided point for equality. The comparison is made using hash of both values to prevent leak of position of mismatching byte.
 * @param other second point for comparison
 * @return true if both point are exactly equal (same length, same value), false otherwise
 */
public boolean isEqual(ECPoint other) {
    boolean bResult = false;
    if (this.length() != other.length()) {
        return false;
    } 
    else {
        // The comparison is made with hash of point values instead of directly values. 
        // This way, offset of first mismatching byte is not leaked via timing side-channel. 
        // Additionally, only single array is required for storage of plain point values thus saving some RAM.            
        ech.lock(ech.uncompressed_point_arr1);
        ech.lock(ech.fnc_isEqual_hashArray);
        //ech.lock(ech.fnc_isEqual_hashEngine);
        short len = this.getW(ech.uncompressed_point_arr1, (short) 0);
        ech.fnc_isEqual_hashEngine.doFinal(ech.uncompressed_point_arr1, (short) 0, len, ech.fnc_isEqual_hashArray, (short) 0);
        len = other.getW(ech.uncompressed_point_arr1, (short) 0);
        len = ech.fnc_isEqual_hashEngine.doFinal(ech.uncompressed_point_arr1, (short) 0, len, ech.uncompressed_point_arr1, (short) 0);
        bResult = Util.arrayCompare(ech.fnc_isEqual_hashArray, (short) 0, ech.uncompressed_point_arr1, (short) 0, len) == 0;
        //ech.unlock(ech.fnc_isEqual_hashEngine);
        ech.unlock(ech.fnc_isEqual_hashArray);
        ech.unlock(ech.uncompressed_point_arr1);
    }

    return bResult;
}
 
Example #4
Source File: CardEdge.java    From SatochipApplet with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This function returns a 2 byte bit mask of the available PINs that are currently in
 * use. Each set bit corresponds to an active PIN.
 * 
 *  ins: 0x48
 *  p1: 0x00
 *  p2: 0x00
 *  data: none
 *  return: [RFU(1b) | PIN_mask(1b)]
 */
private short ListPINs(APDU apdu, byte[] buffer) {
	// check that PIN[0] has been entered previously
	if (!pins[0].isValidated())
		ISOException.throwIt(SW_UNAUTHORIZED);
	
	// Checking P1 & P2
	if (buffer[ISO7816.OFFSET_P1] != (byte) 0x00)
		ISOException.throwIt(SW_INCORRECT_P1);
	if (buffer[ISO7816.OFFSET_P2] != (byte) 0x00)
		ISOException.throwIt(SW_INCORRECT_P2);
	byte expectedBytes = (byte) (buffer[ISO7816.OFFSET_LC]);
	if (expectedBytes != (short) 2)
		ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
	// Build the PIN bit mask
	short mask = (short) 0x00;
	short b;
	for (b = (short) 0; b < MAX_NUM_PINS; b++)
		if (pins[b] != null)
			mask |= (short) (((short) 0x01) << b);
	// Fill the buffer
	Util.setShort(buffer, (short) 0, mask);
	// Send response
	return (short)2;
}
 
Example #5
Source File: ECKeyGenerator.java    From ECTester with MIT License 6 votes vote down vote up
/**
 * @param keypair
 * @param key
 * @param params
 * @param inBuffer
 * @param inOffset
 * @return
 */
public short setExternalCurve(KeyPair keypair, byte key, short params, byte[] inBuffer, short inOffset) {
    sw = ISO7816.SW_NO_ERROR;
    if (params == EC_Consts.PARAMETERS_NONE) {
        return sw;
    }

    short paramMask = EC_Consts.PARAMETER_FP;
    while (paramMask <= EC_Consts.PARAMETER_S) {
        short masked = (short) (paramMask & params);
        if (masked != 0) {
            short paramLength = Util.getShort(inBuffer, inOffset);
            inOffset += 2;
            sw = setParameter(keypair, key, masked, inBuffer, inOffset, paramLength);
            inOffset += paramLength;
            if (sw != ISO7816.SW_NO_ERROR) break;
        }
        paramMask = (short) (paramMask << 1);
    }
    return sw;
}
 
Example #6
Source File: Records.java    From CardExamples with The Unlicense 6 votes vote down vote up
/**
 * Constructor for SFI Record object.
 * 
 * @param sfi
 * @param recordNumber
 * @param data
 * @param dataOffset
 * @param dataLength
 */
private Record(byte sfi, byte recordNumber, byte[] data, short dataOffset, short dataLength) {
    this.sfi = sfi;
    this.recordNumber = recordNumber;

    // Add tag and length to record data.
    short recordLength = (short) (dataLength + (byte) 2);
    if (dataLength > (short) 127) {
        recordLength++;
    }
    this.data = new byte[recordLength];
    // Reuse 'recordLength' to track offset.
    recordLength = (short) 0;
    this.data[recordLength++] = Constants.TAG_READ_RECORD_RESPONSE_MESSAGE_TEMPLATE;
    if (dataLength > (short) 127) {
        this.data[recordLength++] = (byte) 0x81;
    }
    this.data[recordLength++] = (byte) dataLength;
    this.dataLength = Util.arrayCopyNonAtomic(data, dataOffset, this.data, recordLength, dataLength);
}
 
Example #7
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 #8
Source File: PayPass.java    From CardExamples with The Unlicense 6 votes vote down vote up
public void get_data(APDU apdu, byte[] buf) {
    // verify that the class for this instruction is correct
    if ((short) (buf[ISO7816.OFFSET_CLA] & 0xFF) != 0x80)
        ISOException.throwIt(ISO7816.SW_CLA_NOT_SUPPORTED);
    // check state - this command only works in the PERSO state
    if (PROFILE.STATE != PERSO)
        ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    // check that P1 & P2 are correct
    if (buf[ISO7816.OFFSET_P1] != (byte) 0x00 || (byte) buf[ISO7816.OFFSET_P2] != (byte) 0xCF)
        ISOException.throwIt((short) 0x6A88); //referenced data not found
    // build response message
    apdu.setOutgoing();
    apdu.setOutgoingLength((short) 13);

    buf[0] = (byte) 0xCF; //Key Data Tag
    buf[1] = (byte) 11;   //length
    buf[2] = PROFILE.VER_KMC;
    Util.arrayCopyNonAtomic(PROFILE.KMC_ID, (short) 0, buf, (short) 3, (short) 6);
    Util.arrayCopyNonAtomic(PROFILE.CSN, (short) 0, buf, (short) 9, (short) 4);

    apdu.sendBytes((short) 0, (short) 13);
}
 
Example #9
Source File: Crypto.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
/**
 * Fixes the S value of the signature as described in BIP-62 to avoid malleable signatures. It also fixes the all
 * internal TLV length fields. Returns the number of bytes by which the overall signature length changed (0 or -1).
 *
 * @param sig the signature
 * @param off the offset
 * @return the number of bytes by which the signature length changed
 */
short fixS(byte[] sig, short off) {
  short sOff = (short) (sig[(short) (off + 3)] + (short) (off + 5));
  short ret = 0;

  if (sig[sOff] == 33) {
    Util.arrayCopyNonAtomic(sig, (short) (sOff + 2), sig, (short) (sOff + 1), (short) 32);
    sig[sOff] = 32;
    sig[(short)(off + 1)]--;
    ret = -1;
  }

  sOff++;

  if (ret == -1 || ucmp256(sig, sOff, MAX_S, (short) 0) > 0) {
    sub256(S_SUB, (short) 0, sig, sOff, sig, sOff);
  }

  return ret;
}
 
Example #10
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create and initialize the DATA file
 *
 * @param dataSize to be allocated
 * @param init buffer containing initial data
 * @param initOff offset of initial data in buffer
 * @param initLen length of initial data in buffer
 * @return an array for use as the data file
 */
private byte[] makeData(short dataSize, byte[] init, short initOff, short initLen) {
    byte[] data = new byte[dataSize];

    // initialize from init, if provided
    if (FEATURE_INSTALL_PARAMETERS) {
        if (init != null && initLen > 0) {
            // container size
            Util.setShort(data, (short) 0, initLen);
            // initial data
            Util.arrayCopyNonAtomic(init, initOff, data, (short) 2, initLen);
        }
    }

    return data;
}
 
Example #11
Source File: Bignat.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
* Copies {@code other} into this. No size requirements. If {@code other}
* has more digits then the superfluous leading digits of {@code other} are
* asserted to be zero. If this bignat has more digits than its leading
* digits are correctly initilized to zero. This function will not change size 
* attribute of this object.
* 
* @param other
*            Bignat to copy into this object.
*/
public void copy(Bignat other) {
    short this_start, other_start, len;
    if (this.size >= other.size) {
        this_start = (short) (this.size - other.size);
        other_start = 0;
        len = other.size;
    } else {
        this_start = 0;
        other_start = (short) (other.size - this.size);
        len = this.size;
        // Verify here that other have leading zeroes up to other_start
        for (short i = 0; i < other_start; i ++) {
            if (other.value[i] != 0) {
                ISOException.throwIt(ReturnCodes.SW_BIGNAT_INVALIDCOPYOTHER);
            }
        }
    }

    if (this_start > 0) {
        // if this bignat has more digits than its leading digits are initilized to zero
        Util.arrayFillNonAtomic(this.value, (short) 0, this_start, (byte) 0);
    }
    Util.arrayCopyNonAtomic(other.value, other_start, this.value, this_start, len);
}
 
Example #12
Source File: Bip32ObjectManager.java    From SatochipApplet with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Constructor for the Bip32ObjectManager class.
 * 
 * @param nb_elem
 * 			Max number of elements stored in the array
 * @param size_elem
 * 			Size of each element (fixed)
 * @param size_id
 * 			Size of data used to id the object.
 * 			The first size_id bytes of data are used for comparison
 */
public Bip32ObjectManager(short nb_elem, short size_elem, short size_id) {
	if (ptr != null)
		return;
	if (size_id>size_elem)
		return;
	// Allocate the memory
	size= (short) (nb_elem*size_elem);
	ptr = new byte[size];
	empty  = new byte[size_id]; //to efficiently(?) check for empty elements
	Util.arrayFillNonAtomic(empty, (short)0, size_id, (byte)0);
	this.nb_elem_free= nb_elem;
	this.nb_elem_used= (short)0;
	this.size_elem= size_elem;
	this.size_id=size_id;
}
 
Example #13
Source File: TransitApplet.java    From JCMathLib with MIT License 6 votes vote down vote up
/**
 * Generates the session key derivation data from the passed-in host
 * challenge and the card challenge.
 * 
 * @param buffer
 *            The APDU buffer
 */
private void generateKeyDerivationData(byte[] buffer) {
    byte numBytes = buffer[ISO7816.OFFSET_LC];

    if (numBytes < CHALLENGE_LENGTH) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    // Derivation data: [[8-bytes host challenge], [8-bytes card challenge]]

    // Append host challenge (from buffer) to derivation data
    Util.arrayCopy(buffer, ISO7816.OFFSET_CDATA, keyDerivationData,
            (short) 0, CHALLENGE_LENGTH);
    // Append card challenge to derivation data
    Util.arrayCopy(cardChallenge, (short) 0, keyDerivationData,
            CHALLENGE_LENGTH, CHALLENGE_LENGTH);
}
 
Example #14
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 #15
Source File: Bip32Cache.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void storePublic(byte[] path, short pathOffset, byte pathLength, byte[] publicComponent, short publicComponentOffset) {
	Bip32Cache cache = findPath(path, pathOffset, pathLength, false);
	if (!((cache != null) && cache.hasPublic)) {
		if (cache == null) {
			cache = findFree();
			cache.pathLength = pathLength;
			Util.arrayCopy(path, pathOffset, cache.path, (short)0, (short)(pathLength * 4));				
		}
		Util.arrayCopy(publicComponent, publicComponentOffset, cache.publicComponent, (short)0, (short)65);
		cache.hasPublic = true;
	}		
}
 
Example #16
Source File: NdefApplet.java    From openjavacard-ndef with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Process a SELECT command
 *
 * This handles only the one case mandated by the NDEF
 * specification: SELECT FIRST-OR-ONLY BY-FILE-ID.
 *
 * The file ID is specified in the APDU contents. It
 * must be exactly two bytes long and also valid.
 *
 * @param apdu to process
 * @throws ISOException on error
 */
private void processSelect(APDU apdu) throws ISOException {
    byte[] buffer = apdu.getBuffer();
    byte p1 = buffer[ISO7816.OFFSET_P1];
    byte p2 = buffer[ISO7816.OFFSET_P2];

    // we only support what the NDEF spec prescribes
    if(p1 != SELECT_P1_BY_FILEID || p2 != SELECT_P2_FIRST_OR_ONLY) {
        ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
    }

    // receive data
    short lc = apdu.setIncomingAndReceive();

    // check length, must be for a file ID
    if(lc != 2) {
        ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
    }

    // retrieve the file ID
    short fileId = Util.getShort(buffer, ISO7816.OFFSET_CDATA);

    // perform selection if the ID is valid
    if(fileId == FILEID_NDEF_CAPABILITIES || fileId == FILEID_NDEF_DATA) {
        vars[VAR_SELECTED_FILE] = fileId;
    } else {
        ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
    }
}
 
Example #17
Source File: OpenPGPSecureMessaging.java    From javacard-openpgpcard with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Set the MAC session key. Each key is a 16 byte 3DES EDE key. This method 
 * may be called at any time and will immediately replace the session key.
 * 
 * @param buffer byte array containing the session key.
 * @param offset location of the session key in the buffer.
 */
public void setSessionKeyMAC(byte[] buffer, short offset) {
	// Check for empty keys
	if(Util.arrayCompare(buffer, (short)0, EMPTY_KEY, (short)0, KEY_SIZE) == 0) {
		keyMAC.clearKey();
		keyENC.clearKey();
	}
	else {     	
		keyMAC.setKey(buffer, offset);
    
		signer.init(keyMAC, Signature.MODE_SIGN);
		verifier.init(keyMAC, Signature.MODE_VERIFY);
	}
}
 
Example #18
Source File: Crypto.java    From status-keycard with Apache License 2.0 5 votes vote down vote up
/**
 * Derives a private key according to the algorithm defined in BIP32. The BIP32 specifications define some checks
 * to be performed on the derived keys. In the very unlikely event that these checks fail this key is not considered
 * to be valid so the derived key is discarded and this method returns false.
 *
 * @param i the buffer containing the key path element (a 32-bit big endian integer)
 * @param iOff the offset in the buffer
 * @return true if successful, false otherwise
 */
boolean bip32CKDPriv(byte[] i, short iOff, byte[] scratch, short scratchOff, byte[] data, short dataOff, byte[] output, short outOff) {
  short off = scratchOff;

  if (bip32IsHardened(i, iOff)) {
    scratch[off++] = 0;
    off = Util.arrayCopyNonAtomic(data, dataOff, scratch, off, KEY_SECRET_SIZE);
  } else {
    scratch[off++] = ((data[(short) (dataOff + KEY_SECRET_SIZE + KEY_SECRET_SIZE + KEY_PUB_SIZE - 1)] & 1) != 0 ? (byte) 0x03 : (byte) 0x02);
    off = Util.arrayCopyNonAtomic(data, (short) (dataOff + KEY_SECRET_SIZE + KEY_SECRET_SIZE + 1), scratch, off, KEY_SECRET_SIZE);
  }

  off = Util.arrayCopyNonAtomic(i, iOff, scratch, off, (short) 4);

  hmacSHA512(data, (short)(dataOff + KEY_SECRET_SIZE), KEY_SECRET_SIZE, scratch, scratchOff, (short)(off - scratchOff), output, outOff);

  if (ucmp256(output, outOff, SECP256k1.SECP256K1_R, (short) 0) >= 0) {
    return false;
  }

  addm256(output, outOff, data, dataOff, SECP256k1.SECP256K1_R, (short) 0, output, outOff);

  if (isZero256(output, outOff)) {
    return false;
  }

  return true;
}
 
Example #19
Source File: Bip32Cache.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Bip32Cache findPath(byte[] path, short pathOffset, byte pathLength, boolean setLast) {
	for (short i=0; i<CACHE_SIZE; i++) {
		if ((cache[i].pathLength == pathLength) &&
			(Util.arrayCompare(path, pathOffset, cache[i].path, (short)0, (short)(pathLength * 4)) == 0)) {
				if (setLast) {
					lastCacheIndex[0] = (byte)i;
				}
				return cache[i];
		}
	}
	return null;
}
 
Example #20
Source File: Records.java    From CardExamples with The Unlicense 5 votes vote down vote up
/**
 * Find record, retrieve record data, return record data.
 * 
 * @param sfi
 * @param recordNumber
 * @param dataBuffer
 * @return
 */
short getRecordData(byte sfi, short recordNumber, byte[] dataBuffer) {
    byte result = findSFIRecord(sfi, recordNumber);
    if (result == RECORD_FOUND) {
        return Util.arrayCopyNonAtomic(this.foundRecord.data, (short) 0, dataBuffer, (short) 0, this.foundRecord.dataLength);
    }

    // Use offset 1 to indicate error type.
    dataBuffer[(byte) 1] = result;

    // Record not found.
    // dataBuffer[1] = 0x00 if SFI not found.
    //                 0x01 if SFI found, record number not found.
    return (short) -1;
}
 
Example #21
Source File: U2FApplet.java    From CCU2F with Apache License 2.0 5 votes vote down vote up
private void handleSetAttestationCert(APDU apdu) throws ISOException {
    byte[] buffer = apdu.getBuffer();
    short len = apdu.setIncomingAndReceive();
    short dataOffset = apdu.getOffsetCdata();
    short copyOffset = Util.makeShort(buffer[ISO7816.OFFSET_P1], buffer[ISO7816.OFFSET_P2]);
    if ((short)(copyOffset + len) > (short)attestationCertificate.length) {
        ISOException.throwIt(ISO7816.SW_WRONG_DATA);
    }
    Util.arrayCopy(buffer, dataOffset, attestationCertificate, copyOffset, len);
    if ((short)(copyOffset + len) == (short)attestationCertificate.length) {
        attestationCertificateSet = true;
    }
}
 
Example #22
Source File: LedgerWalletApplet.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void handleStorePublicKey(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);
    }
    offset += (short)(derivationSize * 4);
    Crypto.random.generateData(scratch256, (short)32, (short)32);
    signTransientPrivate(scratch256, (short)0, scratch256, (short)32, scratch256, (short)64);
    if (Crypto.verifyPublic(buffer, offset, scratch256, (short)32, scratch256, (short)64)) {
     Bip32Cache.storePublic(buffer, (short)(ISO7816.OFFSET_CDATA + 1), derivationSize, buffer, offset);
    }
    else {
     ISOException.throwIt(ISO7816.SW_WRONG_DATA);
    }
}
 
Example #23
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 #24
Source File: TransmitManager.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
private void Clear(boolean buffer) {
    if (buffer) {
        Util.arrayFillNonAtomic(ram_buf, (short)0, RAM_BUF_SIZE, (byte)0x00);
    }
    chaining_cache[CHAINING_OBJECT_INDEX] = 0;
    chaining_cache[RAM_CHAINING_CACHE_OFFSET_CURRENT_POS] = 0;
    chaining_cache[RAM_CHAINING_CACHE_OFFSET_BYTES_REMAINING] = 0;
    chaining_cache[RAM_CHAINING_CACHE_PUT_DATA_OFFSET] = 0;
    chaining_object[CHAINING_OBJECT] = null;
    chaining_object[PUT_DATA_OBJECT] = null;
}
 
Example #25
Source File: Keycard.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean getPairingData(byte[] data, short offset) {
    if (pairingData[0] == (byte)0) {
        return false;
    }
    Util.arrayCopyNonAtomic(pairingData, (short)1, data, offset, PAIRING_DATA_SIZE);
    pairingData[0] = (byte)0x00;
    return true;
}
 
Example #26
Source File: CardEdge.java    From SatochipApplet with GNU Affero General Public License v3.0 5 votes vote down vote up
/** 
 * This function creates a PIN with parameters specified by the P1, P2 and DATA
 * values. P2 specifies the maximum number of consecutive unsuccessful
 * verifications before the PIN blocks. PIN can be created only if one of the logged identities
 * allows it. 
 * 
 * ins: 0x40
 * p1: PIN number (0x00-0x07)
 * p2: max attempt number
 * data: [PIN_size(1b) | PIN | UBLK_size(1b) | UBLK] 
 * return: none
 */
private short CreatePIN(APDU apdu, byte[] buffer) {
	// check that PIN[0] has been entered previously
	if (!pins[0].isValidated())
		ISOException.throwIt(SW_UNAUTHORIZED);
	
	byte pin_nb = buffer[ISO7816.OFFSET_P1];
	byte num_tries = buffer[ISO7816.OFFSET_P2];
	
	if ((pin_nb < 0) || (pin_nb >= MAX_NUM_PINS) || (pins[pin_nb] != null))
		ISOException.throwIt(SW_INCORRECT_P1);
	/* Allow pin lengths > 127 (useful at all ?) */
	short bytesLeft = Util.makeShort((byte) 0x00, buffer[ISO7816.OFFSET_LC]);
	// At least 1 character for PIN and 1 for unblock code (+ lengths)
	if (bytesLeft < 4)
		ISOException.throwIt(SW_INVALID_PARAMETER);
	byte pin_size = buffer[ISO7816.OFFSET_CDATA];
	if (bytesLeft < (short) (1 + pin_size + 1))
		ISOException.throwIt(SW_INVALID_PARAMETER);
	if (!CheckPINPolicy(buffer, (short) (ISO7816.OFFSET_CDATA + 1), pin_size))
		ISOException.throwIt(SW_INVALID_PARAMETER);
	byte ucode_size = buffer[(short) (ISO7816.OFFSET_CDATA + 1 + pin_size)];
	if (bytesLeft != (short) (1 + pin_size + 1 + ucode_size))
		ISOException.throwIt(SW_INVALID_PARAMETER);
	if (!CheckPINPolicy(buffer, (short) (ISO7816.OFFSET_CDATA + 1 + pin_size + 1), ucode_size))
		ISOException.throwIt(SW_INVALID_PARAMETER);
	pins[pin_nb] = new OwnerPIN(num_tries, PIN_MAX_SIZE);
	pins[pin_nb].update(buffer, (short) (ISO7816.OFFSET_CDATA + 1), pin_size);
	ublk_pins[pin_nb] = new OwnerPIN((byte) 3, PIN_MAX_SIZE);
	// Recycle variable pin_size
	pin_size = (byte) (ISO7816.OFFSET_CDATA + 1 + pin_size + 1);
	ublk_pins[pin_nb].update(buffer, pin_size, ucode_size);
	
	return (short)0;
}
 
Example #27
Source File: GidsPINManager.java    From GidsApplet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * \brief clear the data used for admin authentication
 */
private void ClearChallengeData() {
    Util.arrayFillNonAtomic(ExternalChallenge, (short) 0,   (short) ExternalChallenge.length, (byte)0x00);
    Util.arrayFillNonAtomic(CardChallenge, (short) 0,   (short) CardChallenge.length, (byte)0x00);
    Util.arrayFillNonAtomic(buffer, (short) 0,   (short) buffer.length, (byte)0x00);
    Util.arrayFillNonAtomic(status, (short) 0,   (short) status.length, (byte)0x00);
}
 
Example #28
Source File: JavaCardAES.java    From sim-password-manager with Apache License 2.0 5 votes vote down vote up
private void ShiftRow(byte a[], short dataOffset, byte d) {
  byte i, j;
  // ALSO FIRST ROUND IS SHIFTED (BUT BY 0 POSITIONS) DUE TO POSSIBILITY FOR USING Util.arrayCopy() LATER
  // tempBuffer WILL CONTAINS SHIFTED STATE a
  for(i = 0; i < 4; i++) {
      for(j = 0; j < BLOCKN; j++) tempBuffer[(short) (i + j * 4)] = a[(short) (((i + (byte) ((j + shifts[(short) (i + d*4)] % BLOCKN) * 4)) % STATELEN) + dataOffset)];
  }
  Util.arrayCopyNonAtomic(tempBuffer, (short) 0, a, dataOffset, STATELEN);
}
 
Example #29
Source File: CardEdge.java    From SatochipApplet with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This function allows to set the 2FA key and enable 2FA.
 * Once activated, 2FA can only be deactivated when the seed is reset.
 *  
 *  ins: 0x79
 *  p1: 0x00
 *  p2: 0x00
 *  data: [hmacsha1_key(20b) | amount_limit(8b)]
 *  return: (none)
 */
private short set2FAKey(APDU apdu, byte[] buffer){
	// check that PIN[0] has been entered previously
	if (!pins[0].isValidated())
		ISOException.throwIt(SW_UNAUTHORIZED);
	// cannot modify an existing 2FA!
	if (needs_2FA)
		ISOException.throwIt(SW_2FA_INITIALIZED_KEY);
	
	//check input length
	short bytesLeft = Util.makeShort((byte) 0x00, buffer[ISO7816.OFFSET_LC]);
	if (bytesLeft < (short)(20+8))
		ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
	
	if (!done_once_2FA){
		data2FA= new byte[OFFSET_2FA_SIZE];
		randomData = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
        aes128_cbc= Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
        key_2FA= (AESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);
        done_once_2FA= true;
	}
	
	short offset= ISO7816.OFFSET_CDATA;
	Util.arrayCopyNonAtomic(buffer, offset, data2FA, OFFSET_2FA_HMACKEY, (short)20); 
	offset+=(short)20;
	Util.arrayCopyNonAtomic(buffer, offset, data2FA, OFFSET_2FA_LIMIT, (short)8); 
	offset+=(short)8;
	// hmac derivation for id_2FA & key_2FA
	HmacSha160.computeHmacSha160(data2FA, OFFSET_2FA_HMACKEY, (short)20, CST_2FA, (short)0, (short)6, data2FA, OFFSET_2FA_ID);
       HmacSha160.computeHmacSha160(data2FA, OFFSET_2FA_HMACKEY, (short)20, CST_2FA, (short)6, (short)7, recvBuffer, (short)0);
       key_2FA.setKey(recvBuffer,(short)0); // AES-128: 16-bytes key!!
       needs_2FA= true;	
       
       return (short)0;
}
 
Example #30
Source File: LedgerWalletApplet.java    From ledger-javacard with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void reset() {
    Crypto.random.generateData(scratch256, (short)0, (short)16);
    chipKey.setKey(scratch256, (short)0);
    Util.arrayFillNonAtomic(scratch256, (short)0, (short)16, (byte)0x00);
    setup = TC.FALSE;
    limitsSet = TC.FALSE;
}