Example usage for java.nio.channels SeekableByteChannel position

List of usage examples for java.nio.channels SeekableByteChannel position

Introduction

In this page you can find the example usage for java.nio.channels SeekableByteChannel position.

Prototype

SeekableByteChannel position(long newPosition) throws IOException;

Source Link

Document

Sets this channel's position.

Usage

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

@Override
public Long encryptFile(InputStream plaintextFile, SeekableByteChannel encryptedFile) throws IOException {
    // truncate file
    encryptedFile.truncate(0);//w  ww .  j a va2s  .c  o m

    // use an IV, whose last 8 bytes store a long used in counter mode and write initial value to file.
    final ByteBuffer countingIv = ByteBuffer.wrap(randomData(AES_BLOCK_LENGTH));
    countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, 0l);
    countingIv.position(0);
    encryptedFile.write(countingIv);

    // init crypto stuff:
    final Mac mac = this.hmacSha256(hMacMasterKey);
    final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.ENCRYPT_MODE);

    // init mac buffer and skip 32 bytes
    final ByteBuffer macBuffer = ByteBuffer.allocate(mac.getMacLength());
    encryptedFile.write(macBuffer);

    // init filesize buffer and skip 16 bytes
    final ByteBuffer encryptedFileSizeBuffer = ByteBuffer.allocate(AES_BLOCK_LENGTH);
    encryptedFile.write(encryptedFileSizeBuffer);

    // write content:
    final OutputStream out = new SeekableByteChannelOutputStream(encryptedFile);
    final OutputStream macOut = new MacOutputStream(out, mac);
    final OutputStream cipheredOut = new CipherOutputStream(macOut, cipher);
    final OutputStream blockSizeBufferedOut = new BufferedOutputStream(cipheredOut, AES_BLOCK_LENGTH);
    final Long plaintextSize = IOUtils.copyLarge(plaintextFile, blockSizeBufferedOut);

    // ensure total byte count is a multiple of the block size, in CTR mode:
    final int remainderToFillLastBlock = AES_BLOCK_LENGTH - (int) (plaintextSize % AES_BLOCK_LENGTH);
    blockSizeBufferedOut.write(new byte[remainderToFillLastBlock]);

    // append a few blocks of fake data:
    final int numberOfPlaintextBlocks = (int) Math.ceil(plaintextSize / AES_BLOCK_LENGTH);
    final int upToTenPercentFakeBlocks = (int) Math.ceil(Math.random() * 0.1 * numberOfPlaintextBlocks);
    final byte[] emptyBytes = new byte[AES_BLOCK_LENGTH];
    for (int i = 0; i < upToTenPercentFakeBlocks; i += AES_BLOCK_LENGTH) {
        blockSizeBufferedOut.write(emptyBytes);
    }
    blockSizeBufferedOut.flush();

    // write MAC of total ciphertext:
    macBuffer.position(0);
    macBuffer.put(mac.doFinal());
    macBuffer.position(0);
    encryptedFile.position(16); // right behind the IV
    encryptedFile.write(macBuffer); // 256 bit MAC

    // encrypt and write plaintextSize
    try {
        final ByteBuffer fileSizeBuffer = ByteBuffer.allocate(Long.BYTES);
        fileSizeBuffer.putLong(plaintextSize);
        final Cipher sizeCipher = aesEcbCipher(primaryMasterKey, Cipher.ENCRYPT_MODE);
        final byte[] encryptedFileSize = sizeCipher.doFinal(fileSizeBuffer.array());
        encryptedFileSizeBuffer.position(0);
        encryptedFileSizeBuffer.put(encryptedFileSize);
        encryptedFileSizeBuffer.position(0);
        encryptedFile.position(48); // right behind the IV and MAC
        encryptedFile.write(encryptedFileSizeBuffer);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        throw new IllegalStateException(
                "Block size must be valid, as padding is requested. BadPaddingException not possible in encrypt mode.",
                e);
    }

    return plaintextSize;
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

/**
 * Consumes the content and writes it to the ServletOutputStream.
 *
 * @param content  The source resource// w w  w  .  j  a v  a  2 s.  c om
 * @param out   The outputBufferSize stream to write to
 * @param range     Range the client wanted to retrieve
 */
private static void copy(final MCRContent content, final ServletOutputStream out, final Range range,
        // TODO: beautify this
        final int inputBufferSize, final int outputBufferSize) throws IOException {
    if (content.isReusable()) {
        try (ReadableByteChannel readableByteChannel = content.getReadableByteChannel()) {
            if (readableByteChannel instanceof SeekableByteChannel) {
                endCurrentTransaction();
                SeekableByteChannel seekableByteChannel = (SeekableByteChannel) readableByteChannel;
                seekableByteChannel.position(range.start);
                long bytesToCopy = range.end - range.start + 1;
                while (bytesToCopy > 0) {
                    ByteBuffer byteBuffer;
                    if (bytesToCopy > (long) MCRServletContentHelper.DEFAULT_BUFFER_SIZE) {
                        byteBuffer = ByteBuffer.allocate(MCRServletContentHelper.DEFAULT_BUFFER_SIZE);
                    } else {
                        byteBuffer = ByteBuffer.allocate((int) bytesToCopy);
                    }

                    int bytesRead = seekableByteChannel.read(byteBuffer);
                    bytesToCopy -= bytesRead;
                    out.write(byteBuffer.array());
                }
                return;
            }
        }
    }

    try (final InputStream resourceInputStream = content.getInputStream();
            final InputStream in = isInputStreamBuffered(resourceInputStream, content) ? resourceInputStream
                    : new BufferedInputStream(resourceInputStream, inputBufferSize)) {
        endCurrentTransaction();
        final IOException exception = copyRange(in, out, 0, range.start, range.end, outputBufferSize);
        if (exception != null) {
            throw exception;
        }
    }
}

From source file:srebrinb.compress.sevenzip.SevenZOutputFile.java

/**
 * Prepares channel to write a 7z archive to.
 *
 * <p>{@link/*  w  w  w. j a  v  a  2 s  .  c  om*/
 * org.apache.commons.compress.utils.SeekableInMemoryByteChannel}
 * allows you to write to an in-memory archive.</p>
 *
 * @param channel the channel to write to
 * @throws IOException if the channel cannot be positioned properly
 * @since 1.13
 */
public SevenZOutputFile(final SeekableByteChannel channel) throws IOException {
    this.channel = channel;
    channel.position(SevenZFile.SIGNATURE_HEADER_SIZE);
}