@Override public OutputStream createOutputStream(OutputStream out) throws IOException { if (cipherSession == null) { throw new RuntimeException("Cipher session is not initialized. Call init() before!"); } return new MultiCipherOutputStream(out, cipherSpecs, cipherSession); }
@Override public void write(int b) throws IOException { writeHeader(); cipherOutputStream.write(b); }
private void writeAndUpdateHmac(OutputStream outputStream, int abyte) throws IOException { writeNoHmac(outputStream, abyte); headerHmac.update((byte) abyte); } }
private void writeHeader() throws IOException { if (!headerWritten) { try { // Initialize header HMAC SaltedSecretKey hmacSecretKey = cipherSession.getWriteSecretKey(HMAC_SPEC); headerHmac = Mac.getInstance(HMAC_SPEC.getAlgorithm(), CRYPTO_PROVIDER_ID); headerHmac.init(hmacSecretKey); // Write header writeNoHmac(underlyingOutputStream, STREAM_MAGIC); writeNoHmac(underlyingOutputStream, STREAM_VERSION); writeNoHmac(underlyingOutputStream, hmacSecretKey.getSalt()); writeAndUpdateHmac(underlyingOutputStream, cipherSpecs.size()); cipherOutputStream = underlyingOutputStream; for (CipherSpec cipherSpec : cipherSpecs) { SaltedSecretKey saltedSecretKey = cipherSession.getWriteSecretKey(cipherSpec); byte[] iv = CipherUtil.createRandomArray(cipherSpec.getIvSize()/8); writeAndUpdateHmac(underlyingOutputStream, cipherSpec.getId()); writeAndUpdateHmac(underlyingOutputStream, saltedSecretKey.getSalt()); writeAndUpdateHmac(underlyingOutputStream, iv); cipherOutputStream = cipherSpec.newCipherOutputStream(cipherOutputStream, saltedSecretKey.getEncoded(), iv); } writeNoHmac(underlyingOutputStream, headerHmac.doFinal()); } catch (Exception e) { throw new IOException(e); } headerWritten = true; } }
@Override public void write(byte[] b, int off, int len) throws IOException { writeHeader(); cipherOutputStream.write(b, off, len); }
public static void encrypt(InputStream plaintextInputStream, OutputStream ciphertextOutputStream, List<CipherSpec> cipherSpecs, SaltedSecretKey masterKey) throws CipherException { try { CipherSession cipherSession = new CipherSession(masterKey); OutputStream multiCipherOutputStream = new MultiCipherOutputStream(ciphertextOutputStream, cipherSpecs, cipherSession); int read = -1; byte[] buffer = new byte[4096]; while (-1 != (read = plaintextInputStream.read(buffer))) { multiCipherOutputStream.write(buffer, 0, read); } plaintextInputStream.close(); multiCipherOutputStream.close(); } catch (IOException e) { throw new CipherException(e); } }
private void writeAndUpdateHmac(OutputStream outputStream, byte[] bytes) throws IOException { writeNoHmac(outputStream, bytes); headerHmac.update(bytes); }
@Override public void write(byte[] b) throws IOException { writeHeader(); cipherOutputStream.write(b, 0, b.length); }