Search in sources :

Example 96 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project graal by oracle.

the class VirtualizedFileSystemTest method write.

private static void write(Path path, byte[] content, FileSystem fs) throws IOException {
    final Set<StandardOpenOption> options = EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    try (SeekableByteChannel ch = fs.newByteChannel(path, options)) {
        ByteBuffer bb = ByteBuffer.wrap(content);
        ch.write(bb);
    }
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) StandardOpenOption(java.nio.file.StandardOpenOption) ByteBuffer(java.nio.ByteBuffer)

Example 97 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project tink by google.

the class StreamingTestUtil method tryDecryptModifiedCiphertextWithSeekableByteChannel.

// Methods for testModifiedCiphertextWithSeekableByteChannel.
/**
 * Tries to decrypt a modified ciphertext using an SeekableByteChannel. Each call to read must
 * either return the original plaintext (e.g. when the modification in the ciphertext does not
 * affect the plaintext) or it must throw an IOException.
 */
private static void tryDecryptModifiedCiphertextWithSeekableByteChannel(StreamingAead ags, byte[] modifiedCiphertext, byte[] aad, byte[] plaintext) throws Exception {
    SeekableByteChannel bbc = new SeekableByteBufferChannel(modifiedCiphertext);
    SeekableByteChannel ptChannel;
    // with the current implementation. Hence we don't catch these exceptions at the moment.
    try {
        ptChannel = ags.newSeekableDecryptingChannel(bbc, aad);
    } catch (IOException | GeneralSecurityException ex) {
        return;
    }
    for (int start = 0; start <= plaintext.length; start += 1 + start / 2) {
        for (int length = 1; length <= plaintext.length; length += 1 + length / 2) {
            ByteBuffer pt = ByteBuffer.allocate(length);
            ptChannel.position(start);
            int read;
            try {
                read = ptChannel.read(pt);
            } catch (IOException ex) {
                // However, if later calls return plaintext this has to be valid plaintext.
                continue;
            }
            if (read == -1) {
                // ptChannel claims that we reached the end of the plaintext.
                assertTrue("Incorrect truncation: ", start == plaintext.length);
            } else {
                // Expect the decrypted plaintext not to be longer than the expected plaintext.
                assertTrue("start:" + start + " read:" + read + " length:" + length, start + read <= plaintext.length);
                // Check that the decrypted plaintext matches the original plaintext.
                String expected = TestUtil.hexEncode(Arrays.copyOfRange(plaintext, start, start + pt.position()));
                String actual = TestUtil.hexEncode(Arrays.copyOf(pt.array(), pt.position()));
                assertEquals("start: " + start, expected, actual);
            }
        }
    }
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 98 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project tink by google.

the class StreamingTestUtil method tryDecryptModifiedCiphertext.

// Methods for testModifiedCiphertext.
/**
 * Tries to decrypt a modified ciphertext. Each call to read must either return the original
 * plaintext (e.g. when the modification in the ciphertext has not yet been read) or it must throw
 * an IOException.
 */
private static void tryDecryptModifiedCiphertext(StreamingAead ags, int firstSegmentOffset, byte[] modifiedCiphertext, byte[] aad, int chunkSize, byte[] plaintext) throws Exception {
    SeekableByteChannel ct = new SeekableByteBufferChannel(modifiedCiphertext);
    ct.position(firstSegmentOffset);
    ReadableByteChannel ptChannel = ags.newDecryptingChannel(ct, aad);
    int position = 0;
    int read;
    do {
        ByteBuffer chunk = ByteBuffer.allocate(chunkSize);
        try {
            read = ptChannel.read(chunk);
        } catch (IOException ex) {
            // TODO(bleichen): Maybe check that the stream cannot longer be accessed.
            return;
        }
        if (read > 0) {
            assertTrue("Read more plaintext than expected", position + read <= plaintext.length);
            // Everything decrypted must be equal to the original plaintext.
            TestUtil.assertByteArrayEquals("Returned modified plaintext position:" + position + " size:" + read, Arrays.copyOf(chunk.array(), read), Arrays.copyOfRange(plaintext, position, position + read));
            position += read;
        }
    } while (read >= 0);
    fail("Reached end of plaintext.");
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) ReadableByteChannel(java.nio.channels.ReadableByteChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 99 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project tink by google.

the class StreamingTestUtil method testEncryptDecryptRandomAccess.

// Methods for testEncryptDecryptRandomAccess.
/**
 * Encrypt and then decrypt partially, and check that the result is the same.
 */
public static void testEncryptDecryptRandomAccess(StreamingAead ags, int firstSegmentOffset, int plaintextSize) throws Exception {
    byte[] aad = TestUtil.hexDecode("aabbccddeeff");
    byte[] plaintext = generatePlaintext(plaintextSize);
    byte[] ciphertext = encryptWithChannel(ags, plaintext, aad, firstSegmentOffset);
    // Construct a channel with random access for the ciphertext.
    SeekableByteChannel bbc = new SeekableByteBufferChannel(ciphertext);
    SeekableByteChannel ptChannel = ags.newSeekableDecryptingChannel(bbc, aad);
    for (int start = 0; start < plaintextSize; start += 1 + start / 2) {
        for (int length = 1; length < plaintextSize; length += 1 + length / 2) {
            ByteBuffer pt = ByteBuffer.allocate(length);
            ptChannel.position(start);
            int read = ptChannel.read(pt);
            // Expect that pt is filled unless the end of the plaintext has been reached.
            assertTrue("start:" + start + " read:" + read + " length:" + length, pt.remaining() == 0 || start + pt.position() == plaintext.length);
            String expected = TestUtil.hexEncode(Arrays.copyOfRange(plaintext, start, start + pt.position()));
            String actual = TestUtil.hexEncode(Arrays.copyOf(pt.array(), pt.position()));
            assertEquals("start: " + start, expected, actual);
        }
    }
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) ByteBuffer(java.nio.ByteBuffer)

Example 100 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project tink by google.

the class StreamingTestUtil method testEncryptDecryptString.

// Methods for testEncryptDecryptString.
/**
 * Encrypts and decrypts a with non-ASCII characters using CharsetEncoders and CharsetDecoders.
 */
public static void testEncryptDecryptString(StreamingAead ags) throws Exception {
    byte[] aad = TestUtil.hexDecode("aabbccddeeff");
    String stringWithNonAsciiChars = "αβγδ áéíóúý ∀∑∊∫≅⊕⊄";
    int repetitions = 1000;
    // Encrypts a sequence of strings.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel ctChannel = Channels.newChannel(bos);
    Writer writer = Channels.newWriter(ags.newEncryptingChannel(ctChannel, aad), "UTF-8");
    for (int i = 0; i < repetitions; i++) {
        writer.write(stringWithNonAsciiChars);
    }
    writer.close();
    byte[] ciphertext = bos.toByteArray();
    // Decrypts a sequence of strings.
    // channels.newReader does not always return the requested number of characters.
    SeekableByteChannel ctBuffer = new SeekableByteBufferChannel(ByteBuffer.wrap(ciphertext));
    Reader reader = Channels.newReader(ags.newSeekableDecryptingChannel(ctBuffer, aad), "UTF-8");
    for (int i = 0; i < repetitions; i++) {
        char[] chunk = new char[stringWithNonAsciiChars.length()];
        int position = 0;
        while (position < stringWithNonAsciiChars.length()) {
            int read = reader.read(chunk, position, stringWithNonAsciiChars.length() - position);
            assertTrue("read:" + read, read > 0);
            position += read;
        }
        assertEquals("i:" + i, stringWithNonAsciiChars, new String(chunk));
    }
    int res = reader.read();
    assertEquals(-1, res);
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) WritableByteChannel(java.nio.channels.WritableByteChannel) Reader(java.io.Reader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Writer(java.io.Writer)

Aggregations

SeekableByteChannel (java.nio.channels.SeekableByteChannel)151 ByteBuffer (java.nio.ByteBuffer)72 Path (java.nio.file.Path)56 IOException (java.io.IOException)52 Test (org.junit.Test)41 InputStream (java.io.InputStream)17 ReadableByteChannel (java.nio.channels.ReadableByteChannel)13 NoSuchFileException (java.nio.file.NoSuchFileException)13 FileSystem (java.nio.file.FileSystem)12 StandardOpenOption (java.nio.file.StandardOpenOption)11 Test (org.testng.annotations.Test)9 WritableByteChannel (java.nio.channels.WritableByteChannel)8 OpenOption (java.nio.file.OpenOption)8 HashSet (java.util.HashSet)8 OutputStream (java.io.OutputStream)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 File (java.io.File)6 CloudStorageFileSystem (com.google.cloud.storage.contrib.nio.CloudStorageFileSystem)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 URI (java.net.URI)5