Example usage for javax.crypto CipherInputStream CipherInputStream

List of usage examples for javax.crypto CipherInputStream CipherInputStream

Introduction

In this page you can find the example usage for javax.crypto CipherInputStream CipherInputStream.

Prototype

public CipherInputStream(InputStream is, Cipher c) 

Source Link

Document

Constructs a CipherInputStream from an InputStream and a Cipher.

Usage

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

@Override
public Long decryptedFile(SeekableByteChannel encryptedFile, OutputStream plaintextFile) throws IOException {
    // read iv://from   ww  w.  ja  va2s.  com
    encryptedFile.position(0);
    final ByteBuffer countingIv = ByteBuffer.allocate(AES_BLOCK_LENGTH);
    final int numIvBytesRead = encryptedFile.read(countingIv);

    // read file size:
    final Long fileSize = decryptedContentLength(encryptedFile);

    // check validity of header:
    if (numIvBytesRead != AES_BLOCK_LENGTH || fileSize == null) {
        throw new IOException("Failed to read file header.");
    }

    // go to begin of content:
    encryptedFile.position(64);

    // generate cipher:
    final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.DECRYPT_MODE);

    // read content
    final InputStream in = new SeekableByteChannelInputStream(encryptedFile);
    final InputStream cipheredIn = new CipherInputStream(in, cipher);
    return IOUtils.copyLarge(cipheredIn, plaintextFile, 0, fileSize);
}

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

@Override
public Long decryptRange(SeekableByteChannel encryptedFile, OutputStream plaintextFile, long pos, long length)
        throws IOException {
    // read iv:/*ww  w  . ja  v a 2s . c om*/
    encryptedFile.position(0);
    final ByteBuffer countingIv = ByteBuffer.allocate(AES_BLOCK_LENGTH);
    final int numIvBytesRead = encryptedFile.read(countingIv);

    // check validity of header:
    if (numIvBytesRead != AES_BLOCK_LENGTH) {
        throw new IOException("Failed to read file header.");
    }

    // seek relevant position and update iv:
    long firstRelevantBlock = pos / AES_BLOCK_LENGTH; // cut of fraction!
    long beginOfFirstRelevantBlock = firstRelevantBlock * AES_BLOCK_LENGTH;
    long offsetInsideFirstRelevantBlock = pos - beginOfFirstRelevantBlock;
    countingIv.putLong(AES_BLOCK_LENGTH - Long.BYTES, firstRelevantBlock);

    // fast forward stream:
    encryptedFile.position(64 + beginOfFirstRelevantBlock);

    // generate cipher:
    final Cipher cipher = this.aesCtrCipher(primaryMasterKey, countingIv.array(), Cipher.DECRYPT_MODE);

    // read content
    final InputStream in = new SeekableByteChannelInputStream(encryptedFile);
    final InputStream cipheredIn = new CipherInputStream(in, cipher);
    return IOUtils.copyLarge(cipheredIn, plaintextFile, offsetInsideFirstRelevantBlock, length);
}

From source file:net.tawacentral.roger.secrets.FileUtils.java

/**
 * Read the secrets from the given input stream, decrypting with the given
 * cipher. This uses the old object format and exists for compatibility.
 *
 * @param input The input stream to read the secrets from.
 * @param cipher The cipher to decrypt the secrets with.
 * @return The secrets read from the stream.
 * @throws IOException//from   ww  w.  j  a va 2s . c  o m
 * @throws ClassNotFoundException
 */
@SuppressWarnings("unchecked")
private static ArrayList<Secret> readSecretsV2(InputStream input, Cipher cipher, byte[] salt, int rounds)
        throws IOException, ClassNotFoundException {
    SaltAndRounds pair = getSaltAndRounds(input);
    if (!Arrays.equals(pair.salt, salt) || pair.rounds != rounds) {
        return null;
    }
    ObjectInputStream oin = new ObjectInputStream(new CipherInputStream(input, cipher));
    try {
        return (ArrayList<Secret>) oin.readObject();
    } finally {
        try {
            if (null != oin)
                oin.close();
        } catch (IOException ex) {
        }
    }
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

/**
 * Returns an input stream encrypted with the given symmetric cipher.
 *//*from  ww  w.j  ava2s.  com*/
private static InputStream getEncryptedInputStream(PutObjectRequest request, Cipher symmetricCipher) {
    try {
        InputStream originalInputStream = request.getInputStream();
        if (request.getFile() != null) {
            originalInputStream = new RepeatableFileInputStream(request.getFile());
        }
        return new CipherInputStream(originalInputStream, symmetricCipher);
    } catch (Exception e) {
        throw new LunacloudClientException("Unable to create cipher input stream: " + e.getMessage(), e);
    }
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

public static InputStream getEncryptedInputStream(UploadPartRequest request, Cipher symmetricCipher) {
    try {// w w  w .  j  a  v  a2 s  .  c o m
        InputStream originalInputStream = request.getInputStream();
        if (request.getFile() != null) {
            originalInputStream = new InputSubstream(new RepeatableFileInputStream(request.getFile()),
                    request.getFileOffset(), request.getPartSize(), request.isLastPart());
        }

        originalInputStream = new CipherInputStream(originalInputStream, symmetricCipher);

        if (request.isLastPart() == false) {
            // We want to prevent the final padding from being sent on the stream...
            originalInputStream = new InputSubstream(originalInputStream, 0, request.getPartSize(), false);
        }

        long partSize = request.getPartSize();
        int cipherBlockSize = symmetricCipher.getBlockSize();
        return new ByteRangeCapturingInputStream(originalInputStream, partSize - cipherBlockSize, partSize);
    } catch (Exception e) {
        throw new LunacloudClientException("Unable to create cipher input stream: " + e.getMessage(), e);
    }
}

From source file:com.pari.nm.utils.backup.BackupRestore.java

public boolean decrypt(File backupZipFile, File encrZipFile) throws Exception {
    try {//w  ww.  j a v a2 s. c  om
        FileOutputStream fout = new FileOutputStream(backupZipFile);
        FileInputStream fin = new FileInputStream(encrZipFile);
        Cipher cipher = Cipher.getInstance("DESEDE");

        cipher.init(Cipher.DECRYPT_MODE, getDefaultKey());

        CipherInputStream cin = new CipherInputStream(fin, cipher);
        byte[] buffer = new byte[8192];

        try {
            int read = cin.read(buffer);
            while (read != -1) {
                fout.write(buffer, 0, read);
                read = cin.read(buffer);
            }
        } finally {
            try {
                fout.close();
            } catch (Exception ignore) {
            }

            try {
                cin.close();
            } catch (Exception ignore) {
            }

            try {
                fin.close();
            } catch (Exception ignore) {
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return false;
}

From source file:com.datatorrent.lib.io.fs.AbstractFileOutputOperatorTest.java

private void checkCompressedFile(File file, List<Long> offsets, int startVal, int totalWindows,
        int totalRecords, SecretKey secretKey, byte[] iv) throws IOException {
    FileInputStream fis;/*from w ww .  j a v a 2 s  .  c  o m*/
    InputStream gss = null;
    GZIPInputStream gis = null;
    BufferedReader br = null;

    Cipher cipher = null;
    if (secretKey != null) {
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivps);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    int numWindows = 0;
    try {
        fis = new FileInputStream(file);
        //fis.skip(startOffset);
        gss = fis;
        if (secretKey != null) {
            try {
                /*
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                IvParameterSpec ivps = new IvParameterSpec(iv);
                cipher.init(Cipher.DECRYPT_MODE, secretKey, ivps);
                */
                gss = new CipherInputStream(fis, cipher);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        long startOffset = 0;
        for (long offset : offsets) {
            // Skip initial case in case file is not yet created
            if (offset == 0) {
                continue;
            }
            long limit = offset - startOffset;
            LimitInputStream lis = new LimitInputStream(gss, limit);

            //gis = new GZIPInputStream(fis);
            gis = new GZIPInputStream(lis);
            br = new BufferedReader(new InputStreamReader(gis));
            //br = new BufferedReader(new InputStreamReader(gss));
            String eline = "" + (startVal + numWindows * 2);
            int count = 0;
            String line;
            while ((line = br.readLine()) != null) {
                Assert.assertEquals("File line", eline, line);
                ++count;
                if ((count % totalRecords) == 0) {
                    ++numWindows;
                    eline = "" + (startVal + numWindows * 2);
                }
            }
            startOffset = offset;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            br.close();
        } else {
            if (gis != null) {
                gis.close();
            } else if (gss != null) {
                gss.close();
            }
        }
    }
    Assert.assertEquals("Total", totalWindows, numWindows);
}