Search code examples
javaencryptionpassword-protection7zip

How to check if an InputStream 7Z archive file is password protected or not?


I have used commons-compress-1.21.jar

File f = new File("/home/user/Desktop/test.7z");     
SevenZFile sevenZFile = new SevenZFile(f);
SevenZArchiveEntry entry = sevenZFile.getNextEntry();
sevenZFile.read();
sevenZFile.close();
inMemoryByteChannel.close();

This is working code to identify given test.7z password protected or not. While reading it's throwing:

protectedjava.io.IOException: Cannot read encrypted files without a password
    at org.apache.commons.compress.archivers.sevenz.AES256SHA256Decoder$1.init(AES256SHA256Decoder.java:57)
    at org.apache.commons.compress.archivers.sevenz.AES256SHA256Decoder$1.read(AES256SHA256Decoder.java:118)
    at org.apache.commons.compress.utils.ChecksumVerifyingInputStream.read(ChecksumVerifyingInputStream.java:85)
    at java.io.DataInputStream.readFully(DataInputStream.java:195)
    at java.io.DataInputStream.readFully(DataInputStream.java:169)
    at org.apache.commons.compress.archivers.sevenz.SevenZFile.readEncodedHeader(SevenZFile.java:289)
    at org.apache.commons.compress.archivers.sevenz.SevenZFile.readHeaders(SevenZFile.java:191)
    at org.apache.commons.compress.archivers.sevenz.SevenZFile.<init>(SevenZFile.java:95)
    at org.apache.commons.compress.archivers.sevenz.SevenZFile.<init>(SevenZFile.java:117)
    at com.helloworld.ZipFileTest.main(ZipFileTest.java:45)

From this exception we can identify this is password protected file. But I have only an InputStream of the 7Z file. I don't have the file nor file path.


Solution

  • SevenZFile can accept SeekableByteChannel as parameter.

    Just create SeekableInMemoryByteChannel from your stream.

    InputStream inputStream; // input stream
    SeekableInMemoryByteChannel channel = new SeekableInMemoryByteChannel
           (IOUtils.toByteArray(inputStream));
    

    Source