How to check if xlsx password is protected or not using apache poi

How to check if password is protected by xlsx file or not. we can check the xls file as follows

FileInputStream fin = new FileInputStream(new File("C:/Book1.xls"));
            POIFSFileSystem poifs = new POIFSFileSystem(fin);
            EncryptionInfo info = new EncryptionInfo(poifs);
            Decryptor d = Decryptor.getInstance(info);

            try {
                if (!d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) {
                    throw new RuntimeException("Unable to process: document is encrypted");
                }

                InputStream dataStream = d.getDataStream(poifs);
                HSSFWorkbook wb = new HSSFWorkbook(dataStream);
                // parse dataStream

            } catch (GeneralSecurityException ex) {
                throw new RuntimeException("Unable to process encrypted document", ex);
            }

But the above code only works for xls, not xlsx.

+3
source share
3 answers

If you do not know what you have, but you know the password, you should use WorkbookFactory.create and pass the password to it, for example

Workbook wb = WorkbookFactory.create(new File("protected.xls"),
                                     "NiceSecurePassword");

WorkbookFactorywill identify the type, then will cause the corresponding decryption and downloading of the book for you. If the file is not protected, the password will be ignored.

.

, .xlsx, , , - :

Workbook wb = null;
try {
   wb = new XSSFWorkbook(new File("test.xlsx"));
} catch (EncryptedDocumentException e) {
   // Password protected, try to decrypt and load
}

XSSFWorkbook .xlsx, EncryptedDocumentException, , , ,

+2

XSSFWorkbook wb = new XSSFWorkbook(dataStream);

Apache POI: "HSSF - Java POI Project Excel'97 (-2007). XSSF - Java OOXML (.xlsx) Excel. http://poi.apache.org/spreadsheet/ HSSF ( xls) XLSX.

+1

-,

public boolean isEncrypted(String path) {

    try {
        try {
            new POIFSFileSystem(new FileInputStream(path));
        } catch (IOException ex) {

        }
        System.out.println("protected");
        return true;
    } catch (OfficeXmlFileException e) {
        System.out.println("not protected");
        return false;
    }
}

if (isEncrypted(sourcepath)) {
        org.apache.poi.hssf.record.crypto.Biff8EncryptionKey.setCurrentUserPassword("1234");
        POIFSFileSystem filesystem = new POIFSFileSystem(new FileInputStream(inpFn));
        EncryptionInfo info = new EncryptionInfo(filesystem);
        Decryptor d = Decryptor.getInstance(info);

        if (!d.verifyPassword("1234")) {
            System.out.println("Not good");
        } else {
            System.out.println("Good!");
        }

        in = d.getDataStream(filesystem);
    } else {
        in = new FileInputStream(inpFn);
    }
    try {
        XSSFWorkbook wbIn = new XSSFWorkbook(in);
.
.
.
+1

Source: https://habr.com/ru/post/1535391/


All Articles