This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git

commit c198d6a428310b35de0ab41ccec25279f92be4c4
Author: Gary Gregory <[email protected]>
AuthorDate: Wed Dec 2 15:34:30 2026 -0500

    [7-Zip] Use a fresh IV for each encrypted entry
    
    Derive the AES key once per archive and create independent IVs and
    ciphers for each entry. Track per-entry metadata by object identity
    to preserve encryption properties and sizes when entries are renamed.
    
    Add 33 regression cases covering IV separation, cipher independence,
    entry mutations, codecs, padding boundaries, and password handling.
    Update Javadoc.
---
 src/changes/changes.xml                            |   1 +
 .../compress/archivers/sevenz/AES256Options.java   |  74 ++--
 .../archivers/sevenz/AES256SHA256Decoder.java      |   7 +-
 .../archivers/sevenz/SevenZOutputFile.java         |  20 +-
 .../archivers/sevenz/AES256OptionsTest.java        |  91 +++++
 .../sevenz/SevenZOutputFileEncryptionTest.java     | 384 +++++++++++++++++++++
 6 files changed, 549 insertions(+), 28 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 498dbbba7..85fcea613 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -69,6 +69,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Gary Gregory">[7-Zip] 
SevenZOutputFile now throws ArchiveException instead of 
IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[7-Zip] Correct substream memory accounting, enforce the configured 
memory limit, and reject missing substream sizes.</action>
       <action type="fix" dev="ggregory" due-to="Claude Security, Gary 
Gregory">[7-Zip] Enforce the configured memory limit on decoded header sizes 
before creating decoders, and close archive channels on I/O failures during 
construction.</action>
+      <action type="fix" dev="ggregory">[7-Zip] Use a fresh initialization 
vector for each encrypted entry and preserve per-entry metadata when entries 
are renamed.</action>
       <!-- FIX bzip2 -->
       <action type="fix" dev="ggregory" due-to="Tyler Nighswander, Gary 
Gregory">[BZip2] BZip2CompressorInputStream now throws CompressorException 
instead of IllegalArgumetException/IllegalStateException.</action>
       <action type="fix" dev="pkarwasz" due-to="Tyler Nighswander, Piotr P. 
Karwasz">[BZip2] BZip2 input streams treat Huffman codes longer than 20 bits as 
corrupted data, matching the behavior of the reference implementation.</action>
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256Options.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256Options.java
index ccb58e570..9bb33caed 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256Options.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256Options.java
@@ -62,43 +62,44 @@ private static byte[] randomBytes(final int size) throws 
ArchiveException {
 
     private final int numCyclesPower;
 
-    private final Cipher cipher;
+    private final SecretKey aesKey;
 
     /**
-     * Creates a new AES256Options with a random salt and IV.
+     * Creates encryption options with an empty salt and a random IV.
      *
      * @param password password used for encryption.
-     * @throws ArchiveException No strong secure random available to generate 
strong AES key.
+     * @throws ArchiveException if key derivation or IV generation fails.
      */
     AES256Options(final char[] password) throws ArchiveException {
         this(password, EMPTY_BYTE_ARRAY, randomBytes(16), 19);
     }
 
     /**
+     * Creates encryption options by deriving an AES key from the password.
+     *
      * @param password       password used for encryption.
-     * @param salt           for password hash salting (enforce password 
security).
-     * @param iv             Initialization Vector (IV) used by cipher 
algorithm.
-     * @param numCyclesPower another password security enforcer parameter that 
controls the cycles of password hashing. More the this number is high, more
-     *                       security you'll have but also high CPU usage.
-     * @throws ArchiveException Encryption error (Check JCE Unlimited Strength 
Jurisdiction Policy Files installation).
+     * @param salt           salt used for key derivation.
+     * @param iv             initialization vector used for encryption.
+     * @param numCyclesPower base-2 logarithm of the number of key derivation 
iterations.
+     * @throws ArchiveException if key derivation fails.
      */
     AES256Options(final char[] password, final byte[] salt, final byte[] iv, 
final int numCyclesPower) throws ArchiveException {
+        this(newSecretKeySpec(AES256SHA256Decoder.sha256Password(password, 
numCyclesPower, salt)), salt, iv, numCyclesPower);
+    }
+
+    /**
+     * Creates encryption options using an already derived key.
+     *
+     * @param aesKey         the derived AES key.
+     * @param salt           salt used to derive the key.
+     * @param iv             initialization vector used for encryption.
+     * @param numCyclesPower base-2 logarithm of the number of key derivation 
iterations.
+     */
+    private AES256Options(final SecretKey aesKey, final byte[] salt, final 
byte[] iv, final int numCyclesPower) {
+        this.aesKey = aesKey;
         this.salt = salt;
         this.iv = iv;
         this.numCyclesPower = numCyclesPower;
-        // NOTE: for security purposes, password is wrapped in a Cipher as 
soon as possible to not stay in memory
-        final byte[] aesKeyBytes = 
AES256SHA256Decoder.sha256Password(password, numCyclesPower, salt);
-        final SecretKey aesKey = newSecretKeySpec(aesKeyBytes);
-        try {
-            cipher = Cipher.getInstance(TRANSFORMATION);
-            cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
-        } catch (final GeneralSecurityException e) {
-            throw new ArchiveException("Encryption error (Check JCE Unlimited 
Strength Jurisdiction Policy Files installation).", (Throwable) e);
-        }
-    }
-
-    Cipher getCipher() {
-        return cipher;
     }
 
     byte[] getIv() {
@@ -112,4 +113,35 @@ int getNumCyclesPower() {
     byte[] getSalt() {
         return salt;
     }
+
+    /**
+     * Creates an initialized cipher for one encoder stream.
+     *
+     * @return a new cipher using this key and IV.
+     * @throws ArchiveException if the cipher cannot be initialized.
+     */
+    Cipher newCipher() throws ArchiveException {
+        try {
+            final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
+            cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(iv));
+            return cipher;
+        } catch (final GeneralSecurityException e) {
+            throw new ArchiveException("Encryption error (Check JCE Unlimited 
Strength Jurisdiction Policy Files installation).", (Throwable) e);
+        }
+    }
+
+    /**
+     * Creates options with the same derived key and a fresh random IV.
+     *
+     * <p>
+     * CBC requires an unpredictable IV for each independently encrypted 
stream. Reusing an IV with the same key reveals matching leading blocks of the
+     * encryption input. The salt and cycle count are preserved, and the 
expensive key derivation is not repeated.
+     * </p>
+     *
+     * @return options with a fresh random IV.
+     * @throws ArchiveException if IV generation fails.
+     */
+    AES256Options withFreshIv() throws ArchiveException {
+        return new AES256Options(aesKey, salt, randomBytes(16), 
numCyclesPower);
+    }
 }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java
 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java
index 4c936d6cc..bf0b28fbc 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/AES256SHA256Decoder.java
@@ -142,9 +142,10 @@ private static final class AES256SHA256DecoderOutputStream 
extends OutputStream
         private final byte[] cipherBlockBuffer;
         private int count;
 
-        private AES256SHA256DecoderOutputStream(final AES256Options opts, 
final OutputStream out) {
-            cipherOutputStream = new CipherOutputStream(out, opts.getCipher());
-            cipherBlockSize = opts.getCipher().getBlockSize();
+        private AES256SHA256DecoderOutputStream(final AES256Options opts, 
final OutputStream out) throws ArchiveException {
+            final Cipher cipher = opts.newCipher();
+            cipherOutputStream = new CipherOutputStream(out, cipher);
+            cipherBlockSize = cipher.getBlockSize();
             cipherBlockBuffer = new byte[cipherBlockSize];
         }
 
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
index 136fa3e3f..63920540e 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.java
@@ -44,7 +44,7 @@
 import java.util.Collections;
 import java.util.Date;
 import java.util.EnumSet;
-import java.util.HashMap;
+import java.util.IdentityHashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -128,9 +128,15 @@ private static <T> Iterable<T> reverse(final Iterable<T> 
i) {
     private CountingOutputStream currentOutputStream;
     private CountingOutputStream[] additionalCountingStreams;
     private Iterable<? extends SevenZMethodConfiguration> contentMethods = 
Collections.singletonList(new SevenZMethodConfiguration(SevenZMethod.LZMA2));
-    private final Map<SevenZArchiveEntry, long[]> additionalSizes = new 
HashMap<>();
+    private final Map<SevenZArchiveEntry, long[]> additionalSizes = new 
IdentityHashMap<>();
     private AES256Options aes256Options;
 
+    /**
+     * Stores each entry's encryption options until its folder header is 
written. Entry identity keeps the IV stable when entry metadata changes and 
keeps
+     * distinct entries separate even when they compare equal.
+     */
+    private final Map<SevenZArchiveEntry, AES256Options> entryAes256Options = 
new IdentityHashMap<>();
+
     /**
      * Opens file to write a 7z archive to.
      *
@@ -338,9 +344,15 @@ private Iterable<? extends SevenZMethodConfiguration> 
getContentMethods(final Se
         final Iterable<? extends SevenZMethodConfiguration> ms = 
entry.getContentMethods();
         Iterable<? extends SevenZMethodConfiguration> iter = ms == null ? 
contentMethods : ms;
         if (aes256Options != null) {
-            // prepend encryption
+            AES256Options entryOptions = entryAes256Options.get(entry);
+            if (entryOptions == null) {
+                // Use the initial random IV for the first stream, then 
generate a fresh IV for each subsequent stream.
+                entryOptions = entryAes256Options.isEmpty() ? aes256Options : 
aes256Options.withFreshIv();
+                entryAes256Options.put(entry, entryOptions);
+            }
+            // The encoder and the folder header must use the same IV.
             iter = Stream
-                    .concat(Stream.of(new 
SevenZMethodConfiguration(SevenZMethod.AES256SHA256, aes256Options)), 
StreamSupport.stream(iter.spliterator(), false))
+                    .concat(Stream.of(new 
SevenZMethodConfiguration(SevenZMethod.AES256SHA256, entryOptions)), 
StreamSupport.stream(iter.spliterator(), false))
                     .collect(Collectors.toList());
         }
         return iter;
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256OptionsTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256OptionsTest.java
new file mode 100644
index 000000000..eb179687d
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/AES256OptionsTest.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.commons.compress.archivers.sevenz;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.util.Arrays;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests per-stream AES options and cipher ownership.
+ */
+class AES256OptionsTest {
+
+    @Test
+    void testIndependentCiphers() throws Exception {
+        final AES256Options options = new 
AES256Options("password".toCharArray(), new byte[0], new byte[16], 1);
+        final Cipher first = options.newCipher();
+        final Cipher second = options.newCipher();
+        assertNotSame(first, second);
+        final byte[] block = new byte[16];
+        Arrays.fill(block, (byte) 42);
+        final byte[] expected = options.newCipher().doFinal(block);
+        // Interleave two streams so sharing a mutable cipher would discard 
the first stream's buffered input.
+        first.update(block, 0, 8);
+        assertArrayEquals(expected, second.doFinal(block));
+        assertArrayEquals(expected, first.doFinal(block, 8, 8));
+    }
+
+    @Test
+    void testInvalidIv() throws ArchiveException {
+        final AES256Options options = new 
AES256Options("password".toCharArray(), new byte[0], new byte[1], 1);
+        final ArchiveException exception = 
assertThrows(ArchiveException.class, options::newCipher);
+        assertEquals(InvalidAlgorithmParameterException.class, 
exception.getCause().getClass());
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {0, 1, 5})
+    void testWithFreshIvPreservesKeyDerivationParameters(final int cycles) 
throws Exception {
+        final char[] password = "password".toCharArray();
+        final byte[] salt = {1, 2, 3, 4, 5, 6, 7, 8};
+        final byte[] iv = new byte[16];
+        final AES256Options original = new AES256Options(password, salt, iv, 
cycles);
+        // The caller may discard the password before subsequent entries are 
written.
+        Arrays.fill(password, '\0');
+        final AES256Options fresh = original.withFreshIv();
+        assertNotSame(original, fresh);
+        assertArrayEquals(salt, fresh.getSalt());
+        assertEquals(cycles, fresh.getNumCyclesPower());
+        assertArrayEquals(iv, original.getIv());
+        assertEquals(16, fresh.getIv().length);
+        assertFalse(Arrays.equals(original.getIv(), fresh.getIv()));
+
+        final byte[] plaintext = new byte[32];
+        Arrays.fill(plaintext, (byte) 42);
+        final byte[] encrypted = fresh.newCipher().doFinal(plaintext);
+        final Cipher decoder = 
Cipher.getInstance(AES256Options.TRANSFORMATION);
+        decoder.init(Cipher.DECRYPT_MODE,
+                
AES256Options.newSecretKeySpec(AES256SHA256Decoder.sha256Password("password".toCharArray(),
 cycles, salt)), new IvParameterSpec(fresh.getIv()));
+        assertArrayEquals(plaintext, decoder.doFinal(encrypted));
+        assertFalse(Arrays.equals(original.newCipher().doFinal(plaintext), 
encrypted));
+    }
+}
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileEncryptionTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileEncryptionTest.java
new file mode 100644
index 000000000..56581cfbb
--- /dev/null
+++ 
b/src/test/java/org/apache/commons/compress/archivers/sevenz/SevenZOutputFileEncryptionTest.java
@@ -0,0 +1,384 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.commons.compress.archivers.sevenz;
+
+import static org.apache.commons.lang3.reflect.FieldUtils.readDeclaredField;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.apache.commons.compress.AbstractTest;
+import org.apache.commons.compress.PasswordRequiredException;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * Tests encryption across independent 7z entry streams and their folder 
headers.
+ */
+class SevenZOutputFileEncryptionTest extends AbstractTest {
+
+    private static final char[] PASSWORD = "password".toCharArray();
+
+    /**
+     * Checks the serialized folder IVs and packed streams, rather than the 
writer's cached options.
+     */
+    private static void assertDistinctStreams(final Path path, final int 
count) throws Exception {
+        final byte[] bytes = Files.readAllBytes(path);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            final Archive archive = (Archive) readDeclaredField(in, "archive", 
true);
+            assertEquals(count, archive.folders.length);
+            assertEquals(count, archive.packSizes.length);
+            final byte[][] ivs = new byte[count][];
+            final byte[][] packed = new byte[count][];
+            int offset = Math.toIntExact(SevenZFile.SIGNATURE_HEADER_SIZE + 
archive.packPos);
+            for (int i = 0; i < count; i++) {
+                ivs[i] = getIv(archive.folders[i]);
+                final int end = offset + Math.toIntExact(archive.packSizes[i]);
+                packed[i] = Arrays.copyOfRange(bytes, offset, end);
+                for (int j = 0; j < i; j++) {
+                    assertFalse(Arrays.equals(ivs[j], ivs[i]), "Entries must 
have different IVs");
+                    assertFalse(Arrays.equals(packed[j], packed[i]), "Entries 
must have different ciphertext");
+                    assertFalse(Arrays.equals(Arrays.copyOf(packed[j], 16), 
Arrays.copyOf(packed[i], 16)), "Leading ciphertext blocks must differ");
+                }
+                offset = end;
+            }
+        }
+    }
+
+    private static SevenZArchiveEntry entry(final String name) {
+        final SevenZArchiveEntry entry = new SevenZArchiveEntry();
+        entry.setName(name);
+        return entry;
+    }
+
+    private static byte[] getIv(final Folder folder) {
+        for (final Coder coder : folder.coders) {
+            if (Arrays.equals(SevenZMethod.AES256SHA256.getId(), 
coder.decompressionMethodId)) {
+                final byte[] properties = coder.properties;
+                final int saltSize = (properties[0] >>> 7 & 1) + 
(properties[1] >>> 4 & 0xf);
+                final int ivSize = (properties[0] >>> 6 & 1) + (properties[1] 
& 0xf);
+                assertEquals(16, ivSize);
+                return Arrays.copyOfRange(properties, 2 + saltSize, 2 + 
saltSize + ivSize);
+            }
+        }
+        throw new AssertionError("Missing AES coder");
+    }
+
+    private static byte[] readEntry(final SevenZFile in) throws IOException {
+        final UnsynchronizedByteArrayOutputStream result = 
UnsynchronizedByteArrayOutputStream.builder().get();
+        final byte[] buffer = new byte[1024];
+        int count;
+        while ((count = in.read(buffer)) != -1) {
+            result.write(buffer, 0, count);
+        }
+        return result.toByteArray();
+    }
+
+    private static void writeEntry(final SevenZOutputFile out, final 
SevenZArchiveEntry entry, final byte[] data) throws IOException {
+        out.putArchiveEntry(entry);
+        out.write(data);
+        out.closeArchiveEntry();
+    }
+
+    @ParameterizedTest
+    @ValueSource(ints = {0, 1, 15, 16, 17, 31, 32, 33, 4096})
+    void testCopyPaddingAndWriteBoundaries(final int length) throws Exception {
+        final Path path = newTempPath("copy-padding.7z");
+        final byte[] data = new byte[length];
+        for (int i = 0; i < data.length; i++) {
+            data[i] = (byte) (31 * i + length);
+        }
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(SevenZMethod.COPY);
+            for (int i = 0; i < 3; i++) {
+                out.putArchiveEntry(entry("file-" + i));
+                if (i == 0) {
+                    for (final byte value : data) {
+                        out.write(value);
+                    }
+                } else if (i == 1) {
+                    // Leave a partial block buffered, then exercise the bulk 
write and trailing padding paths.
+                    final int split = Math.min(length, 7);
+                    out.write(data, 0, split);
+                    out.write(data, split, length - split);
+                } else {
+                    out.write(new ByteArrayInputStream(data));
+                }
+                out.closeArchiveEntry();
+            }
+        }
+        assertDistinctStreams(path, length == 0 ? 0 : 3);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            for (int i = 0; i < 3; i++) {
+                assertEquals("file-" + i, in.getNextEntry().getName());
+                assertArrayEquals(data, readEntry(in));
+            }
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testEmptyArchive() throws Exception {
+        final Path path = newTempPath("empty.7z");
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.finish();
+        }
+        assertDistinctStreams(path, 0);
+        try (SevenZFile in = SevenZFile.builder().setPath(path).get()) {
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testEqualEntryObjects() throws Exception {
+        final Path path = newTempPath("equal.7z");
+        final byte[] data = new byte[32];
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(SevenZMethod.COPY);
+            final SevenZArchiveEntry first = entry("duplicate");
+            writeEntry(out, first, data);
+            // Distinct entries can compare equal when their metadata is 
already populated.
+            final SevenZArchiveEntry second = entry("duplicate");
+            second.setHasStream(first.hasStream());
+            second.setHasCrc(first.getHasCrc());
+            second.setSize(first.getSize());
+            second.setCompressedSize(first.getCompressedSize());
+            second.setCrcValue(first.getCrcValue());
+            second.setCompressedCrcValue(first.getCompressedCrcValue());
+            assertNotSame(first, second);
+            assertEquals(first, second);
+            writeEntry(out, second, data);
+        }
+        assertDistinctStreams(path, 2);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            for (int i = 0; i < 2; i++) {
+                assertEquals("duplicate", in.getNextEntry().getName());
+                assertArrayEquals(data, readEntry(in));
+            }
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @EnumSource(value = SevenZMethod.class, names = {"COPY", "LZMA", "LZMA2", 
"DEFLATE", "BZIP2"})
+    void testIdenticalEntries(final SevenZMethod method) throws Exception {
+        final Path path = newTempPath("identical.7z");
+        final byte[] data = new byte[33];
+        Arrays.fill(data, (byte) 42);
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(method);
+            for (int i = 0; i < 3; i++) {
+                writeEntry(out, entry("duplicate"), data);
+            }
+        }
+        assertDistinctStreams(path, 3);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            for (int i = 0; i < 3; i++) {
+                assertEquals("duplicate", in.getNextEntry().getName());
+                assertArrayEquals(data, readEntry(in));
+            }
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testMissingAndWrongPassword() throws IOException {
+        final Path path = newTempPath("password.7z");
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(SevenZMethod.COPY);
+            writeEntry(out, entry("file"), new byte[33]);
+        }
+        try (SevenZFile in = SevenZFile.builder().setPath(path).get()) {
+            assertThrows(PasswordRequiredException.class, () -> {
+                in.getNextEntry();
+                readEntry(in);
+            });
+        }
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword("wrong").get()) {
+            assertThrows(IOException.class, () -> {
+                in.getNextEntry();
+                readEntry(in);
+            });
+        }
+    }
+
+    @Test
+    void testMixedEntriesAndWriteMethods() throws Exception {
+        final Path path = newTempPath("mixed.7z");
+        final int[] lengths = {0, 1, 15, 16, 17, 0, 31, 32, 33, 4096};
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(SevenZMethod.DEFLATE);
+            final SevenZArchiveEntry directory = entry("directory/");
+            directory.setDirectory(true);
+            writeEntry(out, directory, new byte[0]);
+            for (final int length : lengths) {
+                final SevenZArchiveEntry entry = entry("file-" + length);
+                if (length % 2 == 0) {
+                    entry.setContentMethods(Collections.singletonList(new 
SevenZMethodConfiguration(SevenZMethod.COPY)));
+                }
+                final byte[] data = new byte[length];
+                Arrays.fill(data, (byte) length);
+                out.putArchiveEntry(entry);
+                if (length % 3 == 0) {
+                    for (final byte value : data) {
+                        out.write(value);
+                    }
+                } else if (length % 3 == 1) {
+                    final int split = length / 2;
+                    out.write(data, 0, split);
+                    out.write(data, split, length - split);
+                } else {
+                    out.write(new ByteArrayInputStream(data));
+                }
+                out.closeArchiveEntry();
+            }
+        }
+        assertDistinctStreams(path, 8);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            assertTrue(in.getNextEntry().isDirectory());
+            for (final int length : lengths) {
+                assertEquals("file-" + length, in.getNextEntry().getName());
+                final byte[] expected = new byte[length];
+                Arrays.fill(expected, (byte) length);
+                assertArrayEquals(expected, readEntry(in));
+            }
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testOnlyEmptyEntries() throws Exception {
+        final Path path = newTempPath("only-empty.7z");
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            final SevenZArchiveEntry directory = entry("directory/");
+            directory.setDirectory(true);
+            writeEntry(out, directory, new byte[0]);
+            writeEntry(out, entry("empty"), new byte[0]);
+        }
+        assertDistinctStreams(path, 0);
+        try (SevenZFile in = SevenZFile.builder().setPath(path).get()) {
+            assertTrue(in.getNextEntry().isDirectory());
+            final SevenZArchiveEntry entry = in.getNextEntry();
+            assertEquals("empty", entry.getName());
+            assertFalse(entry.hasStream());
+            assertArrayEquals(new byte[0], readEntry(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @CsvSource({"COPY,false", "COPY,true", "LZMA2,false", "LZMA2,true"})
+    void testRenamingEntry(final SevenZMethod method, final boolean 
afterClose) throws Exception {
+        final Path path = newTempPath("renamed.7z");
+        final byte[] data = new byte[33];
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(method);
+            final SevenZArchiveEntry entry = entry("original");
+            out.putArchiveEntry(entry);
+            out.write(data);
+            if (afterClose) {
+                out.closeArchiveEntry();
+            }
+            entry.setName("renamed");
+            if (!afterClose) {
+                out.closeArchiveEntry();
+            }
+            writeEntry(out, entry("second"), data);
+        }
+        assertDistinctStreams(path, 2);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            assertEquals("renamed", in.getNextEntry().getName());
+            assertArrayEquals(data, readEntry(in));
+            assertEquals("second", in.getNextEntry().getName());
+            assertArrayEquals(data, readEntry(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testRenamingUnencryptedEntryWithMultipleCoders() throws IOException {
+        final Path path = newTempPath("unencrypted.7z");
+        final byte[] data = new byte[33];
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile())) {
+            out.setContentMethods(Arrays.asList(new 
SevenZMethodConfiguration(SevenZMethod.COPY), new 
SevenZMethodConfiguration(SevenZMethod.LZMA2)));
+            final SevenZArchiveEntry entry = entry("original");
+            writeEntry(out, entry, data);
+            entry.setName("renamed");
+        }
+        try (SevenZFile in = SevenZFile.builder().setPath(path).get()) {
+            assertEquals("renamed", in.getNextEntry().getName());
+            assertArrayEquals(data, readEntry(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @Test
+    void testSharedPrefixes() throws Exception {
+        final Path path = newTempPath("prefixes.7z");
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
PASSWORD)) {
+            out.setContentCompression(SevenZMethod.COPY);
+            for (int i = 0; i < 2; i++) {
+                final byte[] data = new byte[32];
+                data[16] = (byte) i;
+                writeEntry(out, entry("file-" + i), data);
+            }
+        }
+        assertDistinctStreams(path, 2);
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(PASSWORD).get()) {
+            for (int i = 0; i < 2; i++) {
+                assertEquals("file-" + i, in.getNextEntry().getName());
+                final byte[] expected = new byte[32];
+                expected[16] = (byte) i;
+                assertArrayEquals(expected, readEntry(in));
+            }
+            assertNull(in.getNextEntry());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"", "password", "p\u00e4ss\uD83D\uDD11"})
+    void testSingleEntry(final String password) throws IOException {
+        final Path path = newTempPath("single.7z");
+        final byte[] data = new byte[17];
+        try (SevenZOutputFile out = new SevenZOutputFile(path.toFile(), 
password.toCharArray())) {
+            writeEntry(out, entry("file"), data);
+        }
+        try (SevenZFile in = 
SevenZFile.builder().setPath(path).setPassword(password).get()) {
+            assertNotNull(in.getNextEntry());
+            assertArrayEquals(data, readEntry(in));
+            assertNull(in.getNextEntry());
+        }
+    }
+}

Reply via email to