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(LittleEndianInput dis, EncryptionMode preferredEncryptionMode) throws IOException 

Source Link

Usage

From source file:uk.ac.ucl.cs.cmic.giftcloud.uploader.ExcelWriter.java

License:Open Source License

@Override
protected void saveFile(final File file) throws IOException {
    if (spreadsheetPassword.isPresent() && StringUtils.isNotBlank(new String(spreadsheetPassword.get()))) {
        try {/*from   w  w w .j a  v  a  2s. c om*/
            // Write the unencrypted spreadsheet to an in-memory stream
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            baos.close();

            // Create objects for encryption
            POIFSFileSystem fs = new POIFSFileSystem();
            EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile);
            Encryptor enc = info.getEncryptor();

            // Set the password
            enc.confirmPassword(new String(spreadsheetPassword.get()));

            // Open the in-memory spreadsheet
            InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
            OPCPackage opc = OPCPackage.open(inputStream);
            OutputStream os = enc.getDataStream(fs);
            opc.save(os);
            opc.close();
            inputStream.close();

            // Write the encrypted Excel spreadsheet
            FileOutputStream fos = new FileOutputStream(file);
            fs.writeFilesystem(fos);
            fos.close();
        } catch (InvalidFormatException e) {
            throw new IOException(
                    "Unable to save the patient list file due to the following InvalidFormatException when reading the excel file:"
                            + e.getLocalizedMessage(),
                    e);
        } catch (GeneralSecurityException e) {
            throw new IOException(
                    "Unable to save the patient list file due to the following GeneralSecurityException when reading the excel file:"
                            + e.getLocalizedMessage(),
                    e);
        }
    } else {
        // Write the unencrypted spreadsheet to an in-memory stream
        final FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
    }
}