简体   繁体   中英

How to check if a file is password protected /encrypted or not in java

是否有任何Java API可以检查PDF和Office文件格式-返回受密码保护/加密的文件列表?

You can use POI for office documents encryption.

The below example for Office XML-based formats (.xlsx, .pptx, .docx, ...).

XML-based formats are stored in OLE-package stream "EncryptedPackage". Use org.apache.poi.poifs.crypt.Decryptor to decode file:

EncryptionInfo info = new EncryptionInfo(filesystem);
Decryptor d = Decryptor.getInstance(info);

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

    InputStream dataStream = d.getDataStream(filesystem);

    // parse dataStream

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

If you want to read file encrypted with build-in password, use Decryptor.DEFAULT_PASSWORD.

And you can use iText pdf API to identify the password protected PDF.

Example :

try {
        new PdfReader("C:\\Password_protected.pdf");            
    } catch (BadPasswordException e) {
        System.out.println("PDF is password protected..");
    } catch (Exception e) {
        e.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM