/** * Test tampering of ciphertext followed by write to decrypting CipherOutputStream */ private void testTamperedWrite(AEADBlockCipher cipher, CipherParameters params) throws Exception { cipher.init(true, params); byte[] ciphertext = new byte[cipher.getOutputSize(streamSize)]; cipher.doFinal(ciphertext, cipher.processBytes(new byte[streamSize], 0, streamSize, ciphertext, 0)); // Tamper ciphertext[0] += 1; cipher.init(false, params); ByteArrayOutputStream plaintext = new ByteArrayOutputStream(); OutputStream output = createCipherOutputStream(plaintext, cipher); for (int i = 0; i < ciphertext.length; i++) { output.write(ciphertext[i]); } try { output.close(); fail("Expected invalid ciphertext after tamper and write : " + cipher.getAlgorithmName()); } catch (InvalidCipherTextIOException e) { // Expected } }
private byte[] finaliseCipher() throws InvalidCipherTextIOException { try { finalized = true; return cipher.doFinal(); } catch (GeneralSecurityException e) { throw new InvalidCipherTextIOException("Error finalising cipher", e); } }
public Optional<byte[]> load(Path file, byte[] password) throws IOException { byte[] bs = null; if (Files.exists(file)) { try (InputStream is = fileCryptor.newCipherInputStream(Files.newInputStream(file), password)) { bs = IOUtils.toByteArray(is); } catch (RuntimeCryptoException | InvalidCipherTextIOException ex) { logger.debug("-- load() - exception: ", ex); } } else { logger.debug("-- load() - no file: {}", file); } Optional<byte[]> _bs = Optional.ofNullable(bs); logger.debug("-- load() - file: {} bs: 0x{}", file, _bs.map(Hex::toHexString)); return _bs; }
/** * Test tampering of ciphertext followed by write to decrypting CipherOutputStream */ private void testTamperedWrite(String name, Key key, boolean authenticated, boolean useBc) throws Exception { Cipher encrypt = Cipher.getInstance(name, "BC"); Cipher decrypt = Cipher.getInstance(name, "BC"); encrypt.init(Cipher.ENCRYPT_MODE, key); if (encrypt.getIV() != null) { decrypt.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(encrypt.getIV())); } else { decrypt.init(Cipher.DECRYPT_MODE, key); } byte[] ciphertext = encrypt.doFinal(new byte[1000]); // Tamper ciphertext[0] += 1; ByteArrayOutputStream plaintext = new ByteArrayOutputStream(); OutputStream output = createOutputStream(plaintext, decrypt, useBc); for (int i = 0; i < ciphertext.length; i++) { output.write(ciphertext[i]); } try { output.close(); fail("Expected invalid ciphertext after tamper and write : " + name, authenticated, useBc); } catch (InvalidCipherTextIOException e) { // Expected } }