import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
+import org.apache.commons.io.output.CountingOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.poifs.crypt.ChainingMode;
private final SecretKeySpec skeySpec;
private final byte[] ivBytes;
private final File tempFile;
-
+ private CountingOutputStream outputStream;
+
public EncryptedTempData() throws IOException {
SecureRandom sr = new SecureRandom();
ivBytes = new byte[16];
*/
public OutputStream getOutputStream() throws IOException {
Cipher ciEnc = CryptoFunctions.getCipher(skeySpec, cipherAlgorithm, ChainingMode.cbc, ivBytes, Cipher.ENCRYPT_MODE, PADDING);
- return new CipherOutputStream(new FileOutputStream(tempFile), ciEnc);
+ outputStream = new CountingOutputStream(new CipherOutputStream(new FileOutputStream(tempFile), ciEnc));
+ return outputStream;
}
/**
return new CipherInputStream(new FileInputStream(tempFile), ciDec);
}
+ /**
+ * @return number of bytes stored in the temp data file (the number you should expect after you decrypt the data)
+ */
+ public long getByteCount() {
+ return outputStream == null ? 0 : outputStream.getByteCount();
+ }
+
/**
* Removes the temporarily backing file
*/
@Test
void testRoundTrip() throws Exception {
String text = UUID.randomUUID().toString();
+ byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String filepath = OpenXML4JTestDataSamples.getSampleFileName("sample.docx");
try (OPCPackage p = OPCPackage.open(filepath, PackageAccess.READ)) {
PackagePartName name = new PackagePartName("/test.txt", true);
EncryptedTempFilePackagePart part = new EncryptedTempFilePackagePart(p, name, "text/plain");
try (OutputStream os = part.getOutputStream()) {
- os.write(text.getBytes(StandardCharsets.UTF_8));
+ os.write(bytes);
}
- assertEquals(-1, part.getSize());
+ assertEquals(bytes.length, part.getSize());
try (InputStream is = part.getInputStream()) {
assertEquals(text, new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8));
}
PackagePartName name = new PackagePartName("/test.txt", true);
TempFilePackagePart part = new TempFilePackagePart(p, name, "text/plain");
try (OutputStream os = part.getOutputStream()) {
- os.write(text.getBytes(StandardCharsets.UTF_8));
+ os.write(bytes);
}
assertEquals(bytes.length, part.getSize());
try (InputStream is = part.getInputStream()) {