Example usage for org.apache.poi.poifs.crypt EncryptionInfo EncryptionInfo

List of usage examples for org.apache.poi.poifs.crypt EncryptionInfo EncryptionInfo

Introduction

In this page you can find the example usage for org.apache.poi.poifs.crypt EncryptionInfo EncryptionInfo.

Prototype

public EncryptionInfo(EncryptionMode encryptionMode) 

Source Link

Document

Prepares for encryption, using the given Encryption Mode, and all other parameters as default.

Usage

From source file:com.github.poi.XlsxUtils.java

License:Apache License

public static InputStream decrypt(final InputStream inputStream, final String pwd) throws Exception {
    try {/*from  w  ww  . j  a v a 2 s . c  o  m*/
        POIFSFileSystem fs = new POIFSFileSystem(inputStream);
        EncryptionInfo info = new EncryptionInfo(fs);
        Decryptor d = Decryptor.getInstance(info);
        if (!d.verifyPassword(pwd)) {
            throw new RuntimeException("incorrect password");
        }
        return d.getDataStream(fs);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:com.kplot.web.data.WorkbookFactory.java

License:Apache License

/**
 * Creates a Workbook from the given NPOIFSFileSystem, which may
 *  be password protected//  w ww .  ja va 2  s .  c  om
 *
 *  @param fs The {@link NPOIFSFileSystem} to read the document from
 *  @param password The password that should be used or null if no password is necessary.
 *
 *  @return The created Workbook
 *
 *  @throws IOException if an error occurs while reading the data
 *  @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook}
 */
private static Workbook create(NPOIFSFileSystem fs, String password)
        throws IOException, InvalidFormatException {
    DirectoryNode root = fs.getRoot();

    // Encrypted OOXML files go inside OLE2 containers, is this one?
    if (root.hasEntry(Decryptor.DEFAULT_POIFS_ENTRY)) {
        EncryptionInfo info = new EncryptionInfo(fs);
        Decryptor d = Decryptor.getInstance(info);

        boolean passwordCorrect = false;
        InputStream stream = null;
        try {
            if (password != null && d.verifyPassword(password)) {
                passwordCorrect = true;
            }
            if (!passwordCorrect && d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) {
                passwordCorrect = true;
            }
            if (passwordCorrect) {
                stream = d.getDataStream(root);
            }
        } catch (GeneralSecurityException e) {
            throw new IOException(e);
        }

        if (!passwordCorrect) {
            if (password != null)
                throw new EncryptedDocumentException("Password incorrect");
            else
                throw new EncryptedDocumentException(
                        "The supplied spreadsheet is protected, but no password was supplied");
        }

        OPCPackage pkg = OPCPackage.open(stream);
        return create(pkg);
    }

    // If we get here, it isn't an encrypted XLSX file
    // So, treat it as a regular HSSF XLS one
    if (password != null) {
        Biff8EncryptionKey.setCurrentUserPassword(password);
    }
    try {
        return new HSSFWorkbook(root, true);
    } finally {
        Biff8EncryptionKey.setCurrentUserPassword(null);
    }
}

From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java

License:Apache License

public void initializeWorkbook() throws Exception {
    if (inputFile != null) {
        // open existing files
        if (currentType == SpreadsheetTyp.XLS) {
            if (readPassword != null) {
                try {
                    // switch on decryption
                    Biff8EncryptionKey.setCurrentUserPassword(readPassword);
                    FileInputStream fin = new FileInputStream(inputFile);
                    workbook = new HSSFWorkbook(fin);
                    fin.close();//from w  ww  . j  ava 2s  .c  o  m
                } finally {
                    // switch off
                    Biff8EncryptionKey.setCurrentUserPassword(null);
                    readPassword = null;
                }
            } else {
                FileInputStream fin = new FileInputStream(inputFile);
                workbook = new HSSFWorkbook(fin);
                fin.close();
            }
        } else if (currentType == SpreadsheetTyp.XLSX) {
            if (createStreamingXMLWorkbook) {
                FileInputStream fin = new FileInputStream(inputFile);
                try {
                    ZipSecureFile.setMinInflateRatio(0);
                    workbook = new SXSSFWorkbook(new XSSFWorkbook(fin), rowAccessWindow);
                } finally {
                    if (fin != null) {
                        try {
                            fin.close();
                        } catch (IOException ioe) {
                            // ignore
                        }
                    }
                }
            } else {
                if (readPassword != null) {
                    FileInputStream fin = new FileInputStream(inputFile);
                    POIFSFileSystem filesystem = new POIFSFileSystem(fin);
                    EncryptionInfo info = new EncryptionInfo(filesystem);
                    Decryptor d = Decryptor.getInstance(info);
                    InputStream dataStream = null;
                    try {
                        if (!d.verifyPassword(readPassword)) {
                            throw new Exception(
                                    "Unable to process: document is encrypted and given password does not match!");
                        }
                        // decrypt 
                        dataStream = d.getDataStream(filesystem);
                        // use open input stream
                        workbook = new XSSFWorkbook(dataStream);
                        dataStream.close();
                    } catch (GeneralSecurityException ex) {
                        throw new Exception("Unable to read and parse encrypted document", ex);
                    } finally {
                        if (dataStream != null) {
                            try {
                                dataStream.close();
                            } catch (IOException ioe) {
                                // ignore
                            }
                        }
                        if (fin != null) {
                            try {
                                fin.close();
                            } catch (IOException ioe) {
                                // ignore
                            }
                        }
                    }
                    readPassword = null;
                } else {
                    FileInputStream fin = new FileInputStream(inputFile);
                    try {
                        workbook = new XSSFWorkbook(fin);
                    } finally {
                        if (fin != null) {
                            try {
                                fin.close();
                            } catch (IOException ioe) {
                                // ignore
                            }
                        }
                    }
                }
            }
        }
    } else {
        // create new workbooks
        if (currentType == SpreadsheetTyp.XLS) {
            workbook = new HSSFWorkbook();
        } else if (currentType == SpreadsheetTyp.XLSX) {
            if (createStreamingXMLWorkbook) {
                workbook = new SXSSFWorkbook(new XSSFWorkbook(), rowAccessWindow);
            } else {
                workbook = new XSSFWorkbook();
            }
        }
    }
    setupDataFormatStyle();
}

From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java

License:Apache License

private static void encryptFile(String inFilePath, String outFilePath, String password) throws Exception {
    if (password == null || password.trim().isEmpty()) {
        throw new Exception("Password cannot be null or empty!");
    }// ww w .ja  v a 2 s. co m
    if (inFilePath == null || inFilePath.trim().isEmpty()) {
        throw new Exception("Input file cannot be null or empty!");
    }
    File inFile = new File(inFilePath);
    if (outFilePath == null || outFilePath.trim().isEmpty()) {
        throw new Exception("Output file cannot be null or empty!");
    }
    File outFile = new File(outFilePath);
    if (inFile.exists() == false) {
        throw new Exception("Excel file to encrypt: " + inFile.getAbsolutePath() + " does not exists!");
    }
    ensureDirExists(outFile);
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword(password);
    OPCPackage opc = OPCPackage.open(inFile, PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    FileOutputStream fos = null;
    Exception ex = null;
    try {
        fos = new FileOutputStream(outFile);
        fs.writeFilesystem(fos);
    } catch (Exception e) {
        ex = e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    }
    if (ex != null) {
        throw ex;
    }
}

From source file:mj.ocraptor.extraction.tika.parser.microsoft.OfficeParser.java

License:Apache License

protected void parse(DirectoryNode root, ParseContext context, Metadata metadata, XHTMLContentHandler xhtml)
        throws IOException, SAXException, TikaException {

    // Parse summary entries first, to make metadata available early
    new SummaryExtractor(metadata).parseSummaries(root);

    // Parse remaining document entries
    POIFSDocumentType type = POIFSDocumentType.detectType(root);

    if (type != POIFSDocumentType.UNKNOWN) {
        setType(metadata, type.getType());
    }/*www .  java  2s .c  om*/

    switch (type) {
    case SOLIDWORKS_PART:
        // new SolidworksExtractor(context).parse(root, xhtml);
        break;
    case SOLIDWORKS_ASSEMBLY:
        break;
    case SOLIDWORKS_DRAWING:
        break;
    case PUBLISHER:
        PublisherTextExtractor publisherTextExtractor = new PublisherTextExtractor(root);
        xhtml.element("p", publisherTextExtractor.getText());
        break;
    case WORDDOCUMENT:
        new WordExtractor(context, metadata).parse(root, xhtml);
        break;
    case POWERPOINT:
        new HSLFExtractor(context, metadata).parse(root, xhtml);
        break;
    case WORKBOOK:
    case XLR:
        Locale locale = context.get(Locale.class, Locale.getDefault());
        new ExcelExtractor(context, metadata).parse(root, xhtml, locale);
        break;
    case PROJECT:
        // We currently can't do anything beyond the metadata
        break;
    case VISIO:
        VisioTextExtractor visioTextExtractor = new VisioTextExtractor(root);
        for (String text : visioTextExtractor.getAllText()) {
            xhtml.element("p", text);
        }
        break;
    case OUTLOOK:
        OutlookExtractor extractor = new OutlookExtractor(root, context);
        extractor.parse(xhtml, metadata);
        break;
    case ENCRYPTED:
        EncryptionInfo info = new EncryptionInfo(root);
        Decryptor d = Decryptor.getInstance(info);

        try {
            // By default, use the default Office Password
            String password = Decryptor.DEFAULT_PASSWORD;

            // If they supplied a Password Provider, ask that for the password,
            // and use the provider given one if available (stick with default if
            // not)
            PasswordProvider passwordProvider = context.get(PasswordProvider.class);
            if (passwordProvider != null) {
                String suppliedPassword = passwordProvider.getPassword(metadata);
                if (suppliedPassword != null) {
                    password = suppliedPassword;
                }
            }

            // Check if we've the right password or not
            if (!d.verifyPassword(password)) {
                throw new EncryptedDocumentException();
            }

            // Decrypt the OLE2 stream, and delegate the resulting OOXML
            // file to the regular OOXML parser for normal handling
            OOXMLParser parser = new OOXMLParser();

            parser.parse(d.getDataStream(root), new EmbeddedContentHandler(new BodyContentHandler(xhtml)),
                    metadata, context);
        } catch (GeneralSecurityException ex) {
            throw new EncryptedDocumentException(ex);
        }
    }
}

From source file:org.apache.tika.parser.microsoft.OfficeParser.java

License:Apache License

protected void parse(DirectoryNode root, ParseContext context, Metadata metadata, XHTMLContentHandler xhtml)
        throws IOException, SAXException, TikaException {

    // Parse summary entries first, to make metadata available early
    new SummaryExtractor(metadata).parseSummaries(root);

    // Parse remaining document entries
    POIFSDocumentType type = POIFSDocumentType.detectType(root);

    if (type != POIFSDocumentType.UNKNOWN) {
        setType(metadata, type.getType());
    }//w  w w.j  a v a2 s .  com

    switch (type) {
    case SOLIDWORKS_PART:
    case SOLIDWORKS_ASSEMBLY:
    case SOLIDWORKS_DRAWING:
        break;
    case PUBLISHER:
        PublisherTextExtractor publisherTextExtractor = new PublisherTextExtractor(root);
        xhtml.element("p", publisherTextExtractor.getText());
        break;
    case WORDDOCUMENT:
        new WordExtractor(context).parse(root, xhtml);
        break;
    case POWERPOINT:
        new HSLFExtractor(context).parse(root, xhtml);
        break;
    case WORKBOOK:
    case XLR:
        Locale locale = context.get(Locale.class, Locale.getDefault());
        new ExcelExtractor(context, metadata).parse(root, xhtml, locale);
        break;
    case PROJECT:
        // We currently can't do anything beyond the metadata
        break;
    case VISIO:
        VisioTextExtractor visioTextExtractor = new VisioTextExtractor(root);
        for (String text : visioTextExtractor.getAllText()) {
            xhtml.element("p", text);
        }
        break;
    case OUTLOOK:
        OutlookExtractor extractor = new OutlookExtractor(root, context);

        extractor.parse(xhtml, metadata);
        break;
    case ENCRYPTED:
        EncryptionInfo info = new EncryptionInfo(root);
        Decryptor d = Decryptor.getInstance(info);

        try {
            // By default, use the default Office Password
            String password = Decryptor.DEFAULT_PASSWORD;

            // If they supplied a Password Provider, ask that for the password,
            //  and use the provider given one if available (stick with default if not)
            PasswordProvider passwordProvider = context.get(PasswordProvider.class);
            if (passwordProvider != null) {
                String suppliedPassword = passwordProvider.getPassword(metadata);
                if (suppliedPassword != null) {
                    password = suppliedPassword;
                }
            }

            // Check if we've the right password or not
            if (!d.verifyPassword(password)) {
                throw new EncryptedDocumentException();
            }

            // Decrypt the OLE2 stream, and delegate the resulting OOXML
            //  file to the regular OOXML parser for normal handling
            OOXMLParser parser = new OOXMLParser();

            parser.parse(d.getDataStream(root), new EmbeddedContentHandler(new BodyContentHandler(xhtml)),
                    metadata, context);
        } catch (GeneralSecurityException ex) {
            throw new EncryptedDocumentException(ex);
        }
    default:
        // For unsupported / unhandled types, just the metadata
        //  is extracted, which happened above
        break;
    }
}

From source file:org.docx4j.openpackaging.packages.OpcPackage.java

License:Apache License

/**
 * convenience method to load a word2007 document 
 * from an existing inputstream (.docx/.docxm, .ppxtx or Flat OPC .xml).
 * // w  ww .  j a va2 s . co m
 * @param is
 * @param docxFormat
 * @return
 * @throws Docx4JException
 * 
 * @Since 3.1.0      
 */
private static OpcPackage load(PackageIdentifier pkgIdentifier, final InputStream is, Filetype type,
        String password) throws Docx4JException {

    if (pkgIdentifier == null) {
        pkgIdentifier = new PackageIdentifierTransient("pkg_" + System.currentTimeMillis());
    }

    StartEvent startEvent = new StartEvent(pkgIdentifier, WellKnownProcessSteps.PKG_LOAD);
    startEvent.publish();

    if (type.equals(Filetype.ZippedPackage)) {

        final ZipPartStore partLoader = new ZipPartStore(is);
        final Load3 loader = new Load3(partLoader);
        OpcPackage opcPackage = loader.get();

        if (pkgIdentifier != null) {
            opcPackage.setName(pkgIdentifier.name());
        }

        new EventFinished(startEvent).publish();
        return opcPackage;

        //         final LoadFromZipNG loader = new LoadFromZipNG();
        //         return loader.get(is);         

    } else if (type.equals(Filetype.Compound)) {

        try {
            POIFSFileSystem fs = new POIFSFileSystem(is);
            EncryptionInfo info = new EncryptionInfo(fs);
            Decryptor d = Decryptor.getInstance(info);
            d.verifyPassword(password);

            InputStream is2 = d.getDataStream(fs);
            final LoadFromZipNG loader = new LoadFromZipNG();
            return loader.get(is2);

        } catch (java.security.InvalidKeyException e) {
            /* Wrong password results in:
             * 
               Caused by: java.security.InvalidKeyException: No installed provider supports this key: (null)
              at javax.crypto.Cipher.a(DashoA13*..)
              at javax.crypto.Cipher.init(DashoA13*..)
              at javax.crypto.Cipher.init(DashoA13*..)
              at org.apache.poi.poifs.crypt.AgileDecryptor.getCipher(AgileDecryptor.java:216)
              at org.apache.poi.poifs.crypt.AgileDecryptor.access$200(AgileDecryptor.java:39)
              at org.apache.poi.poifs.crypt.AgileDecryptor$ChunkedCipherInputStream.<init>(AgileDecryptor.java:127)
              at org.apache.poi.poifs.crypt.AgileDecryptor.getDataStream(AgileDecryptor.java:103)
              at org.apache.poi.poifs.crypt.Decryptor.getDataStream(Decryptor.java:85)              
             */
            throw new Docx4JException("Problem reading compound file: wrong password?", e);
        } catch (Exception e) {
            throw new Docx4JException("Problem reading compound file", e);
        } finally {
            new EventFinished(startEvent).publish();
        }
    }

    try {
        FlatOpcXmlImporter xmlPackage = new FlatOpcXmlImporter(is);
        return xmlPackage.get();
    } catch (final Exception e) {
        OpcPackage.log.error(e.getMessage(), e);
        throw new Docx4JException("Couldn't load xml from stream ", e);
    } finally {
        new EventFinished(startEvent).publish();
    }
}

From source file:org.talend.dataprep.schema.xls.streaming.StreamingWorkbookReader.java

License:Open Source License

public void init(File f) {
    try {//from  www .  ja  va2  s .  c  o m
        if (builder.getPassword() != null) {
            // Based on: https://poi.apache.org/encryption.html
            POIFSFileSystem poifs = new POIFSFileSystem(f);
            EncryptionInfo info = new EncryptionInfo(poifs);
            Decryptor d = Decryptor.getInstance(info);
            d.verifyPassword(builder.getPassword());
            pkg = OPCPackage.open(d.getDataStream(poifs));
        } else {
            pkg = OPCPackage.open(f);
        }

        XSSFReader reader = new XSSFReader(pkg);

        SharedStringsTable sst = reader.getSharedStringsTable();
        StylesTable styles = reader.getStylesTable();

        loadSheets(reader, sst, styles, builder.getRowCacheSize());
    } catch (IOException e) {
        throw new OpenException("Failed to open file", e);
    } catch (OpenXML4JException | XMLStreamException e) {
        throw new ReadException("Unable to read workbook", e);
    } catch (GeneralSecurityException e) {
        throw new ReadException("Unable to read workbook - Decryption failed", e);
    }
}