Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

In this page you can find the example usage for java.nio ByteBuffer put.

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

/**
 * Returns the number of uris read, no of uris remaining to be read.
 *//* w  w w.jav  a 2s  .  c  o m*/
private byte[] getBlobUrisHelper(int pin, Set<URI> uris, byte nread) {
    ByteBuffer buf = ByteBuffer.allocate(14);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.listBlobs, 0, 0, 0, 0, 5 });
    buf.put(this.pinToByteArr(pin));
    buf.put(new byte[] { nread, 0, 0 }); //first arg is how many URIs we read so far.
    buf.position(0);
    try {
        if (printInput)
            System.out.println("Input for listBlobs: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from listBlobs: " + response);
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return null;
        }
        byte[] data = response.getData();
        System.out.println("data: " + Arrays.toString(data));
        int index = 0;
        while (true) {
            if ((index + 2) == data.length) {
                //at the end, so the last two bytes is the updated number of read URIs and the number of unread URIs
                //               System.out.println("data.length: " + data.length);
                //               System.out.println("index: " + index);
                nread = data[index];
                byte unread = data[index + 1];
                System.out.println("nread: " + nread);
                System.out.println("unread: " + unread);
                return new byte[] { nread, unread };
            } else {
                byte uriSize = data[index];
                byte[] uri = new byte[uriSize];
                System.arraycopy(data, index + 1, uri, 0, uriSize);
                uris.add(this.byteArrToUri(uri));
                index += uriSize + 1;
            }
        }
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public SmartcardStatusCode allocateCredential(int pin, URI credentialId, URI issuerParameters) {
    byte[] credIdBytes = null;
    credIdBytes = this.uriToByteArr(credentialId);
    if (credIdBytes.length > 199) {
        return SmartcardStatusCode.REQUEST_URI_TOO_LONG;
    }/*from w  ww.  j  av a2 s . co m*/

    byte issuerID = this.getIssuerIDFromUri(pin, issuerParameters);
    byte newCredentialID = this.getNewCredentialID(pin);
    if (newCredentialID == (byte) -1) {
        return SmartcardStatusCode.INSUFFICIENT_STORAGE;
    }
    ByteBuffer buf = ByteBuffer.allocate(11);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.setCredential, 0, 0, 6 });
    buf.put(this.pinToByteArr(pin));
    buf.put(newCredentialID);
    buf.put(issuerID);
    buf.position(0);
    try {
        if (printInput)
            System.out.println("Input for setCredential: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from setCredential: " + response);
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return this.evaluateStatus(response);
        }
    } catch (CardException e) {
        e.printStackTrace();
        return SmartcardStatusCode.NOT_FOUND;
    }

    //Then store the mapping from credentialURI to credentialID:
    TimingsLogger.logTiming("HardwareSmartcard.storeCredentialUriAndID", true);
    SmartcardStatusCode code = this.storeCredentialUriAndID(pin, credentialId, newCredentialID);
    TimingsLogger.logTiming("HardwareSmartcard.storeCredentialUriAndID", false);
    if (code != SmartcardStatusCode.OK) {
        System.err.println(
                "Credential stored correctly on card, but storing the Uri/ID failed with code: " + code);
        return code;
    }

    return SmartcardStatusCode.OK;
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public SmartcardStatusCode deleteBlob(int pin, URI uri) {
    byte[] uriBytes = null;
    uriBytes = this.uriToByteArr(uri);
    if (uriBytes.length > 199) {
        return SmartcardStatusCode.REQUEST_URI_TOO_LONG;
    }/*from   w  w  w. j a  v  a  2s  . c o  m*/
    // BLOB CACHE!
    blobCache.remove(uri);
    blobUrisCache.remove(uri);

    byte[] data = new byte[4 + uriBytes.length];
    System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
    System.arraycopy(uriBytes, 0, data, 4, uriBytes.length);
    ByteBuffer buf = ByteBuffer.allocate(9 + uriBytes.length);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.removeBlob, 0, 0, (byte) data.length });
    buf.put(data);
    buf.position(0);
    try {
        if (printInput)
            System.out.println("Input for removeBlob: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from removeBlob: " + response);
        return this.evaluateStatus(response);
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.healthmarketscience.jackcess.IndexData.java

/**
 * Writes the index definitions into a table definition buffer.
 * @param buffer Buffer to write to//w  ww .  j a v  a 2  s  .c  o  m
 * @param indexes List of IndexBuilders to write definitions for
 */
protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer) throws IOException {
    ByteBuffer rootPageBuffer = creator.getPageChannel().createPageBuffer();
    writeDataPage(rootPageBuffer, SimpleIndexData.NEW_ROOT_DATA_PAGE, creator.getTdefPageNumber(),
            creator.getFormat());

    for (IndexBuilder idx : creator.getIndexes()) {
        buffer.putInt(MAGIC_INDEX_NUMBER); // seemingly constant magic value

        // write column information (always MAX_COLUMNS entries)
        List<IndexBuilder.Column> idxColumns = idx.getColumns();
        for (int i = 0; i < MAX_COLUMNS; ++i) {

            short columnNumber = COLUMN_UNUSED;
            byte flags = 0;

            if (i < idxColumns.size()) {

                // determine column info
                IndexBuilder.Column idxCol = idxColumns.get(i);
                flags = idxCol.getFlags();

                // find actual table column number
                for (Column col : creator.getColumns()) {
                    if (col.getName().equalsIgnoreCase(idxCol.getName())) {
                        columnNumber = col.getColumnNumber();
                        break;
                    }
                }
                if (columnNumber == COLUMN_UNUSED) {
                    // should never happen as this is validated before
                    throw new IllegalArgumentException("Column with name " + idxCol.getName() + " not found");
                }
            }

            buffer.putShort(columnNumber); // table column number
            buffer.put(flags); // column flags (e.g. ordering)
        }

        TableCreator.IndexState idxState = creator.getIndexState(idx);

        buffer.put(idxState.getUmapRowNumber()); // umap row
        ByteUtil.put3ByteInt(buffer, creator.getUmapPageNumber()); // umap page

        // write empty root index page
        creator.getPageChannel().writePage(rootPageBuffer, idxState.getRootPageNumber());

        buffer.putInt(idxState.getRootPageNumber());
        buffer.putInt(0); // unknown
        buffer.put(idx.getFlags()); // index flags (unique, etc.)
        ByteUtil.forward(buffer, 5); // unknown
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public SmartcardBlob getBlob(int pin, URI uri) {
    //this.resetCard();

    uri = URI.create(uri.toString().replaceAll(":", "_"));
    byte[] uriBytes = this.uriToByteArr(uri);
    if (uriBytes.length > 199) {
        throw new RuntimeException("URI is too long. Cannot have been stored on smartcard.");
    }//  w  w w. j  a v  a2  s  .c  o m

    // BLOB CACHE!
    if (blobCache.containsKey(uri)) {
        SmartcardBlob cached = blobCache.get(uri);
        System.out.println("Cached readBlob: " + uri + " : " + cached.blob.length); // Arrays.toString(cached.blob));
        return cached;
    }
    ByteBuffer buf = ByteBuffer.allocate(9 + 4 + uriBytes.length);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.readBlob, 0, 0, 0 });
    buf.put(this.intLengthToShortByteArr(uriBytes.length + 4));
    buf.put(this.pinToByteArr(pin));
    buf.put(uriBytes);
    buf.put(new byte[] { 0, 0 });
    buf.position(0);
    try {
        if (printInput)
            System.out.println("Input for readBlob: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from readBlob: " + response);
        if (this.evaluateStatus(response) == SmartcardStatusCode.OK) {
            SmartcardBlob blob = new SmartcardBlob();
            blob.blob = response.getData();

            // BLOB CACHE!
            blobCache.put(uri, blob);
            return blob;
        } else {
            return null;
        }
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public BigInteger computeScopeExclusivePseudonym(int pin, URI scope) {
    if (cachedScopeExclusivePseudonym.containsKey(scope)) {
        BigInteger pv = cachedScopeExclusivePseudonym.get(scope);
        System.out.println("Cached from getScopeExclusivePseudonym: " + scope + " : " + pv);
        return pv;
    }/*from  ww  w .  ja  va  2 s .  co  m*/
    try {
        byte[] scopeBytes = this.uriToByteArr(scope);
        if (scopeBytes.length > 2044) {
            throw new RuntimeException("The inputted scope is too large.");
        }
        byte[] begin = new byte[] { (byte) this.ABC4TRUSTCMD, this.getScopeExclusivePseudonym, 0, 0, 0 };
        ByteBuffer buf = ByteBuffer.allocate(9 + 4 + scopeBytes.length);
        buf.put(begin);
        buf.put(this.intLengthToShortByteArr(4 + scopeBytes.length));
        buf.put(this.pinToByteArr(pin));
        buf.put(scopeBytes);
        buf.put(new byte[] { 0, 0 });
        buf.position(0);

        if (printInput)
            System.out.println("Input for getScopeExclusivePseudonym: " + Arrays.toString(buf.array()));
        TimingsLogger.logTiming("HardwareSmartcard.transmitCommand(getScopeExclusivePseudonym)", true);
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        TimingsLogger.logTiming("HardwareSmartcard.transmitCommand(getScopeExclusivePseudonym)", false);
        System.out.println("Response from getScopeExclusivePseudonym: " + response);
        if (this.evaluateStatus(response) == SmartcardStatusCode.OK) {
            BigInteger pv = new BigInteger(1, response.getData());
            cachedScopeExclusivePseudonym.put(scope, pv);
            return pv;
        }
        return null;
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public SmartcardStatusCode storeBlob(int pin, URI uri, SmartcardBlob blob) {
    //this.resetCard();

    String[] forbiddenChars = new String[] { "\u0167", ":", "*", "?", "<", ">", " ", "|" };
    if (uri.toString().contains(":") && !uri.toString().contains("_")) {
        uri = URI.create(uri.toString().replaceAll(":", "_")); //change all ':' to '_'
    } else {/*from  w  w w  . j  a va 2s  . c  o m*/
        for (int i = 0; i < forbiddenChars.length; i++) {
            if (uri.toString().contains(forbiddenChars[i])) {
                throw new RuntimeException(
                        "Cannot store a blob under a URI containing the following char: " + forbiddenChars[i]);
            }
        }
    }
    byte[] uriBytes = null;
    uriBytes = this.uriToByteArr(uri);
    if (uriBytes.length > 199) {
        return SmartcardStatusCode.REQUEST_URI_TOO_LONG;
    }

    // BLOB CACHE!
    blobCache.put(uri, blob);
    blobUrisCache.add(uri);

    //first put data from blob followed by the STORE BLOB command
    this.putData(blob.blob);

    byte[] data = new byte[4 + uriBytes.length];
    System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
    System.arraycopy(uriBytes, 0, data, 4, uriBytes.length);
    ByteBuffer buf = ByteBuffer.allocate(9 + uriBytes.length);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.storeBlob, 0, 0, (byte) data.length });
    buf.put(data);
    buf.position(0);
    try {
        if (printInput)
            System.out.println("Input for storeBlob: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from storeBlob: " + response);
        if ((response.getSW1() != STATUS_OK) && (response.getSW1() != STATUS_BAD_PIN)) {
            throw new InsufficientStorageException("Could not store blob. Response from card: " + response);
        }
        return this.evaluateStatus(response);
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public byte[] getChallenge(int size) {
    //TODO: Make this work for challenge sizes of 256 (or 0)
    if ((size > 256) || (size < 1)) {
        System.err.println("Argument 'size' for getChallenge should be in the range [1,256]");
        return null;
    }/*from w w w .  j  av  a  2  s  .  co  m*/
    try {
        int realSize = size;
        if (realSize == 256) {
            realSize = 0;
        }
        ByteBuffer buf = ByteBuffer.allocate(7);
        System.out.println("Le: " + (byte) size);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.getChallenge, 0, 0, 1, (byte) realSize, 0 });
        buf.position(0);
        System.out.println("Input for getChallenge: " + Arrays.toString(buf.array()));
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from getChallenge: " + response);
        if (this.evaluateStatus(response) == SmartcardStatusCode.OK) {
            return response.getData();
        } else {
            return null;
        }
    } catch (CardException e) {
        return null;
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

@Override
public ZkProofResponse finalizeZkProof(int pin, byte[] challengeHashPreimage, Set<URI> credentialIDs,
        Set<URI> scopeExclusivePseudonyms, byte[] nonceCommitment) {
    byte[] data = new byte[4 + 1 + 1 + 16 + challengeHashPreimage.length]; //pin, prooverID, d which is the number of proofs, proofsession and h
    System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
    data[4] = 1; //TODO: ProoverID - Hardcoded for now
    data[5] = 1; //number of proofs - hardcoded to 1 for pilot.
    System.out.println("nonce length: " + nonceCommitment.length);
    System.out.println("data length: " + data.length);
    System.arraycopy(nonceCommitment, 0, data, 6, 16);
    System.arraycopy(challengeHashPreimage, 0, data, 4 + 1 + 1 + 16, challengeHashPreimage.length);

    ByteBuffer buf = ByteBuffer.allocate(7 + data.length);
    buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.startResponses, 0, 0, 0 });
    buf.put(this.intLengthToShortByteArr(data.length));
    buf.put(data);/*  w w  w .j a  v  a 2  s. co  m*/
    buf.position(0);
    if (printInput)
        System.out.println("Input for startResponses: " + Arrays.toString(buf.array()));
    try {
        ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
        System.out.println("Response from startResponses: " + response);
        System.out.println("And this is the output: " + Arrays.toString(response.getData()));
        if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
            return null;
        }
    } catch (CardException e) {
        e.printStackTrace();
        return null;
    }

    ZkProofResponse zkpr = new ZkProofResponse();

    zkpr.responseForDeviceSecret = this.computeDevicePublicKeyResponse(pin);

    //For Get issuance response
    for (URI uri : credentialIDs) {
        byte credID = this.getCredentialIDFromUri(pin, uri);
        byte[] credInfo = readCredential(pin, credID);
        byte status = credInfo[5];
        String command = "getIssuanceResponse";
        byte issueOrPresent = this.getIssuanceResponse;
        if (status >= 2) {
            System.out.println("Presentation. Status: " + status);
            //credential has already been issued, so we want to present response.
            command = "getPresentationResponse";
            issueOrPresent = this.getPresentationResponse;
        }
        buf = ByteBuffer.allocate(14);
        buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, issueOrPresent, 0, 0, 0, 0, 5 });
        buf.put(this.pinToByteArr(pin));
        buf.put(credID);
        buf.put(new byte[] { 0, 0 });
        buf.position(0);
        try {
            if (printInput)
                System.out.println("Input for " + command + ": " + Arrays.toString(buf.array()));
            ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
            System.out.println("Response from " + command + ": " + response);
            if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
                return null;
            }
            System.out.println("data returned: size: " + response.getData().length + " value: "
                    + Arrays.toString(response.getData()));
            byte[] zx = new byte[response.getNr() / 2];
            byte[] zv = new byte[response.getNr() / 2];
            System.arraycopy(response.getData(), 0, zx, 0, zx.length);
            System.arraycopy(response.getData(), zx.length, zv, 0, zv.length);
            System.out.println("zx: " + Arrays.toString(zx));
            System.out.println("zv: " + Arrays.toString(zv));
            zkpr.responseForCourses.put(uri, new BigInteger(1, zv));
            zkpr.responseForDeviceSecret = new BigInteger(1, zx);
        } catch (CardException e) {
            e.printStackTrace();
            return null;
        }
    }

    return zkpr;
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

public SmartcardStatusCode issueCredentialOnSmartcard(int pin, byte credID) {
    byte[] credInfo = this.readCredential(pin, credID);
    byte status = credInfo[5];
    if (status == 0) {
        try {//from  w w w .j a  v a2s. c  om
            //Start commitments
            byte[] data = new byte[5];
            System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
            data[4] = 1; //ProverID - TODO: hardcoded to 1 as of now. Assuming there can be only 1 for the pilot
            ByteBuffer buf = ByteBuffer.allocate(11);
            buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.startCommitments, 0, 0, 5 });
            buf.put(data);
            buf.put((byte) 16);
            buf.position(0);
            if (printInput)
                System.out.println("Input for startCommitments: " + Arrays.toString(buf.array()));
            ResponseAPDU response = this.transmitCommand(new CommandAPDU(buf));
            System.out.println("Response from startCommitments: " + response);
            System.out.println("And this is the output: " + Arrays.toString(response.getData()));
            byte[] proofSession = response.getData();
            if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
                return this.evaluateStatus(response);
            }

            //Issue the credential
            buf = ByteBuffer.allocate(14);
            buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, getIssuanceCommitment, 0, 0, 0, 0, 5 });
            buf.put(this.pinToByteArr(pin));
            buf.put(credID);
            buf.put(new byte[] { 0, 0 });
            buf.position(0);

            if (printInput)
                System.out.println("Input for getIssuanceCommitment: " + Arrays.toString(buf.array()));
            response = this.transmitCommand(new CommandAPDU(buf));
            System.out.println("Response from getIssuanceCommitment: " + response);
            if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
                return this.evaluateStatus(response);
            }

            //Start responses
            data = new byte[4 + 1 + 1 + 16 + 1]; //pin, prooverID, d which is the number of proofs, proofsession and h
            System.arraycopy(this.pinToByteArr(pin), 0, data, 0, 4);
            data[4] = 1; //TODO: ProoverID - Hardcoded for now
            data[5] = 1; //number of proofs - hardcoded to 1 for pilot.
            System.arraycopy(proofSession, 0, data, 6, 16);

            buf = ByteBuffer.allocate(7 + data.length);
            buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, this.startResponses, 0, 0, 0 });
            buf.put(this.intLengthToShortByteArr(data.length));
            buf.put(data);
            buf.position(0);
            if (printInput)
                System.out.println("Input for startResponses: " + Arrays.toString(buf.array()));
            response = this.transmitCommand(new CommandAPDU(buf));
            System.out.println("Response from startResponses: " + response);
            if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
                return this.evaluateStatus(response);
            }

            //Set status of cred to 2 - issued finalized
            buf = ByteBuffer.allocate(14);
            buf.put(new byte[] { (byte) this.ABC4TRUSTCMD, getIssuanceResponse, 0, 0, 0, 0, 5 });
            buf.put(this.pinToByteArr(pin));
            buf.put(credID);
            buf.put(new byte[] { 0, 0 });
            buf.position(0);
            if (printInput)
                System.out.println("Input for getIssuanceResponse: " + Arrays.toString(buf.array()));
            response = this.transmitCommand(new CommandAPDU(buf));
            System.out.println("Response from getIssuanceResponse: " + response);
            if (this.evaluateStatus(response) != SmartcardStatusCode.OK) {
                return this.evaluateStatus(response);
            }
            credInfo = this.readCredential(pin, credID);
            status = credInfo[5];
            System.out.println(
                    "After issuing the credential with ID " + credID + ", it now has status: " + status);
        } catch (CardException e) {
            throw new RuntimeException("issueCred on smartcard failed.", e);
        }
    } else {
        System.out.println("Warn: Credential on sc attempted issued, but was already issued");
    }
    return SmartcardStatusCode.OK;
}