Example usage for org.bouncycastle.util Arrays copyOfRange

List of usage examples for org.bouncycastle.util Arrays copyOfRange

Introduction

In this page you can find the example usage for org.bouncycastle.util Arrays copyOfRange.

Prototype

public static BigInteger[] copyOfRange(BigInteger[] original, int from, int to) 

Source Link

Usage

From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper.java

License:Open Source License

/**
 * Call DECIPHER command//from  ww  w  .  j av a2 s .c o m
 *
 * @param encryptedSessionKey the encoded session key
 * @return the decoded session key
 */
public byte[] decryptSessionKey(@NonNull byte[] encryptedSessionKey) throws IOException {
    if (!mPw1ValidatedForDecrypt) {
        verifyPin(0x82); // (Verify PW1 with mode 82 for decryption)
    }

    // Transmit
    byte[] data = Arrays.copyOfRange(encryptedSessionKey, 2, encryptedSessionKey.length);
    if (data[0] != 0) {
        data = Arrays.prepend(data, (byte) 0x00);
    }

    CommandAPDU command = new CommandAPDU(0x00, 0x2A, 0x80, 0x86, data, MAX_APDU_NE_EXT);
    ResponseAPDU response = communicate(command);

    if (response.getSW() != APDU_SW_SUCCESS) {
        throw new CardException("Deciphering with Security token failed on receive", response.getSW());
    }

    return response.getData();
}

From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenHelper.java

License:Open Source License

/**
 * Transceives APDU/* w  w w .  ja va  2s .co  m*/
 * Splits extended APDU into short APDUs and chains them if necessary
 * Performs GET RESPONSE command(ISO/IEC 7816-4 par.7.6.1) on retrieving if necessary
 * @param apdu short or extended APDU to transceive
 * @return response from the card
 * @throws IOException
 */
private ResponseAPDU communicate(CommandAPDU apdu) throws IOException {
    ByteArrayOutputStream result = new ByteArrayOutputStream();

    ResponseAPDU lastResponse = null;
    // Transmit
    if (mCardCapabilities.hasExtended()) {
        lastResponse = mTransport.transceive(apdu);
    } else if (apdu.getData().length <= MAX_APDU_NC) {
        int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
        lastResponse = mTransport.transceive(
                new CommandAPDU(apdu.getCLA(), apdu.getINS(), apdu.getP1(), apdu.getP2(), apdu.getData(), ne));
    } else if (apdu.getData().length > MAX_APDU_NC && mCardCapabilities.hasChaining()) {
        int offset = 0;
        byte[] data = apdu.getData();
        int ne = Math.min(apdu.getNe(), MAX_APDU_NE);
        while (offset < data.length) {
            int curLen = Math.min(MAX_APDU_NC, data.length - offset);
            boolean last = offset + curLen >= data.length;
            int cla = apdu.getCLA() + (last ? 0 : MASK_CLA_CHAINING);

            lastResponse = mTransport.transceive(new CommandAPDU(cla, apdu.getINS(), apdu.getP1(), apdu.getP2(),
                    Arrays.copyOfRange(data, offset, offset + curLen), ne));

            if (!last && lastResponse.getSW() != APDU_SW_SUCCESS) {
                throw new UsbTransportException("Failed to chain apdu");
            }

            offset += curLen;
        }
    }
    if (lastResponse == null) {
        throw new UsbTransportException("Can't transmit command");
    }

    result.write(lastResponse.getData());

    // Receive
    while (lastResponse.getSW1() == APDU_SW1_RESPONSE_AVAILABLE) {
        // GET RESPONSE ISO/IEC 7816-4 par.7.6.1
        CommandAPDU getResponse = new CommandAPDU(0x00, 0xC0, 0x00, 0x00, lastResponse.getSW2());
        lastResponse = mTransport.transceive(getResponse);
        result.write(lastResponse.getData());
    }

    result.write(lastResponse.getSW1());
    result.write(lastResponse.getSW2());

    return new ResponseAPDU(result.toByteArray());
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.CcidTransceiver.java

License:Open Source License

public byte[] receiveRaw() throws UsbTransportException {
    byte[] bytes;
    do {/*  w  w w .j a  va 2  s .c o  m*/
        bytes = receive();
    } while (isDataBlockNotReady(bytes));

    checkDataBlockResponse(bytes);

    return Arrays.copyOfRange(bytes, 10, bytes.length);
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.CcidTransceiver.java

License:Open Source License

/**
 * Transmits XfrBlock/*from  w  ww . j  av  a  2  s  .c o  m*/
 * 6.1.4 PC_to_RDR_XfrBlock
 * @param payload payload to transmit
 * @throws UsbTransportException
 */
public void sendXfrBlock(byte[] payload) throws UsbTransportException {
    int l = payload.length;
    byte[] data = Arrays.concatenate(new byte[] { 0x6f, (byte) l, (byte) (l >> 8), (byte) (l >> 16),
            (byte) (l >> 24), 0x00, mCounter++, 0x00, 0x00, 0x00 }, payload);

    int send = 0;
    while (send < data.length) {
        final int len = Math.min(mBulkIn.getMaxPacketSize(), data.length - send);
        sendRaw(Arrays.copyOfRange(data, send, send + len));
        send += len;
    }
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.tpdu.Block.java

License:Open Source License

public byte[] getEdc() {
    return Arrays.copyOfRange(mData, mData.length - mChecksumType.getLength(), mData.length);
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.tpdu.Block.java

License:Open Source License

public byte[] getApdu() {
    return Arrays.copyOfRange(mData, OFFSET_DATA, mData.length - mChecksumType.getLength());
}

From source file:org.sufficientlysecure.keychain.securitytoken.usb.tpdu.T1TpduProtocol.java

License:Open Source License

public byte[] transceive(@NonNull byte[] apdu) throws UsbTransportException {
    int start = 0;

    if (apdu.length == 0) {
        throw new UsbTransportException("Cant transcive zero-length apdu(tpdu)");
    }//  w  w  w. j a  v  a2 s  .co m

    Block responseBlock = null;
    while (apdu.length - start > 0) {
        boolean hasMore = start + MAX_FRAME_LEN < apdu.length;
        int len = Math.min(MAX_FRAME_LEN, apdu.length - start);

        // Send next frame
        Block block = newIBlock(mCounter++, hasMore, Arrays.copyOfRange(apdu, start, start + len));

        mTransceiver.sendXfrBlock(block.getRawData());

        // Receive I or R block
        responseBlock = getBlockFromResponse(mTransceiver.receiveRaw());

        start += len;

        if (responseBlock instanceof SBlock) {
            Log.d(Constants.TAG, "S-Block received " + responseBlock.toString());
            // just ignore
        } else if (responseBlock instanceof RBlock) {
            Log.d(Constants.TAG, "R-Block received " + responseBlock.toString());
            if (((RBlock) responseBlock).getError() != RBlock.RError.NO_ERROR) {
                throw new UsbTransportException("R-Block reports error " + ((RBlock) responseBlock).getError());
            }
        } else { // I block
            if (start != apdu.length) {
                throw new UsbTransportException("T1 frame response underflow");
            }
            break;
        }
    }

    // Receive
    if (responseBlock == null || !(responseBlock instanceof IBlock))
        throw new UsbTransportException("Invalid tpdu sequence state");

    byte[] responseApdu = responseBlock.getApdu();

    while (((IBlock) responseBlock).getChaining()) {
        Block ackBlock = newRBlock((byte) (((IBlock) responseBlock).getSequence() + 1));
        mTransceiver.sendXfrBlock(ackBlock.getRawData());

        responseBlock = getBlockFromResponse(mTransceiver.receiveRaw());

        if (responseBlock instanceof IBlock) {
            responseApdu = Arrays.concatenate(responseApdu, responseBlock.getApdu());
        } else {
            Log.d(Constants.TAG, "Response block received " + responseBlock.toString());
            throw new UsbTransportException("Response: invalid state - invalid block received");
        }
    }

    return responseApdu;
}

From source file:org.sufficientlysecure.keychain.securitytoken.UsbTransport.java

License:Open Source License

/**
 * Transmit and receive data/*from   ww w .j  a  v a2s .  c  om*/
 * @param data data to transmit
 * @return received data
 * @throws UsbTransportException
 */
@Override
public byte[] transceive(byte[] data) throws UsbTransportException {
    sendXfrBlock(data);
    byte[] bytes;
    do {
        bytes = receive();
    } while (isDataBlockNotReady(bytes));

    checkDataBlockResponse(bytes);
    // Discard header
    return Arrays.copyOfRange(bytes, 10, bytes.length);
}

From source file:org.sufficientlysecure.keychain.securitytoken.UsbTransport.java

License:Open Source License

/**
 * Transmits XfrBlock/*  w w  w  .  j  av a2  s  . co m*/
 * 6.1.4 PC_to_RDR_XfrBlock
 * @param payload payload to transmit
 * @throws UsbTransportException
 */
private void sendXfrBlock(byte[] payload) throws UsbTransportException {
    int l = payload.length;
    byte[] data = Arrays.concatenate(new byte[] { 0x6f, (byte) l, (byte) (l >> 8), (byte) (l >> 16),
            (byte) (l >> 24), 0x00, mCounter++, 0x00, 0x00, 0x00 }, payload);

    int send = 0;
    while (send < data.length) {
        final int len = Math.min(mBulkIn.getMaxPacketSize(), data.length - send);
        sendRaw(Arrays.copyOfRange(data, send, send + len));
        send += len;
    }
}

From source file:tor.TorCrypto.java

License:Open Source License

/**
 * Tor Hybrid Encrypt function//from www . j  a va  2 s  .  com
 *
 * @param in Data to encrypt
 * @param pk Onion Router public key to encrypt to
 * @return Encrypted data
 */
public static byte[] hybridEncrypt(byte[] in, PublicKey pk) {
    try {
        Cipher rsa = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
        rsa.init(Cipher.ENCRYPT_MODE, pk);
        if (in.length < PK_ENC_LEN - PK_PAD_LEN) {
            return rsa.doFinal(in);
        } else {
            // prep key and IV
            byte[] key = new byte[KEY_LEN];
            rnd.nextBytes(key);
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            SecretKeySpec keysp = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            // prepare m1
            byte m1a[] = Arrays.copyOfRange(in, 0, PK_ENC_LEN - PK_PAD_LEN - KEY_LEN);
            byte m1[] = ArrayUtils.addAll(key, m1a);
            byte rsaciphertext[] = rsa.doFinal(m1);

            // prepare m2
            byte m2[] = Arrays.copyOfRange(in, m1a.length, in.length);
            Cipher aes = Cipher.getInstance("AES/CTR/NoPadding");
            aes.init(Cipher.ENCRYPT_MODE, keysp, ivSpec);
            byte aesciphertext[] = aes.doFinal(m2);

            // merge
            return ArrayUtils.addAll(rsaciphertext, aesciphertext);
        }
    } catch (BadPaddingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}