org.apache.poi.poifs.crypt.Encryptor Java Examples
The following examples show how to use
org.apache.poi.poifs.crypt.Encryptor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WriteContextImpl.java From easyexcel with Apache License 2.0 | 6 votes |
private POIFSFileSystem openFileSystemAndEncrypt(File file) throws Exception { POIFSFileSystem fileSystem = new POIFSFileSystem(); Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor(); encryptor.confirmPassword(writeWorkbookHolder.getPassword()); OPCPackage opcPackage = null; try { opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE); OutputStream outputStream = encryptor.getDataStream(fileSystem); opcPackage.save(outputStream); } finally { if (opcPackage != null) { opcPackage.close(); } } return fileSystem; }
Example #2
Source File: Poi3Test.java From easyexcel with Apache License 2.0 | 6 votes |
@Test public void Encryption() throws Exception { String file = TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx"; POIFSFileSystem fs = new POIFSFileSystem(); EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); Encryptor enc = info.getEncryptor(); enc.confirmPassword("foobaa"); OPCPackage opc = OPCPackage.open(new File(file), PackageAccess.READ_WRITE); OutputStream os = enc.getDataStream(fs); opc.save(os); opc.close(); // Write out the encrypted version FileOutputStream fos = new FileOutputStream("D:\\test\\99999999999.xlsx"); fs.writeFilesystem(fos); fos.close(); fs.close(); }
Example #3
Source File: XOREncryptionInfoBuilder.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void initialize(EncryptionInfo info, LittleEndianInput dis) throws IOException { info.setHeader(new XOREncryptionHeader()); info.setVerifier(new XOREncryptionVerifier(dis)); Decryptor dec = new XORDecryptor(); dec.setEncryptionInfo(info); info.setDecryptor(dec); Encryptor enc = new XOREncryptor(); enc.setEncryptionInfo(info); info.setEncryptor(enc); }
Example #4
Source File: XOREncryptionInfoBuilder.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) { info.setHeader(new XOREncryptionHeader()); info.setVerifier(new XOREncryptionVerifier()); Decryptor dec = new XORDecryptor(); dec.setEncryptionInfo(info); info.setDecryptor(dec); Encryptor enc = new XOREncryptor(); enc.setEncryptionInfo(info); info.setEncryptor(enc); }
Example #5
Source File: HSSFWorkbook.java From lams with GNU General Public License v2.0 | 5 votes |
private void updateEncryptionInfo() { // make sure, that we've read all the streams ... readProperties(); FilePassRecord fpr = (FilePassRecord)workbook.findFirstRecordBySid(FilePassRecord.sid); String password = Biff8EncryptionKey.getCurrentUserPassword(); WorkbookRecordList wrl = workbook.getWorkbookRecordList(); if (password == null) { if (fpr != null) { // need to remove password data wrl.remove(fpr); } } else { // create password record if (fpr == null) { fpr = new FilePassRecord(EncryptionMode.cryptoAPI); wrl.add(1, fpr); } // check if the password has been changed EncryptionInfo ei = fpr.getEncryptionInfo(); EncryptionVerifier ver = ei.getVerifier(); byte encVer[] = ver.getEncryptedVerifier(); Decryptor dec = ei.getDecryptor(); Encryptor enc = ei.getEncryptor(); try { if (encVer == null || !dec.verifyPassword(password)) { enc.confirmPassword(password); } else { byte verifier[] = dec.getVerifier(); byte salt[] = ver.getSalt(); enc.confirmPassword(password, null, null, verifier, salt, null); } } catch (GeneralSecurityException e) { throw new EncryptedDocumentException("can't validate/update encryption setting", e); } } }
Example #6
Source File: AttachmentExportUtil.java From myexcel with Apache License 2.0 | 5 votes |
/** * 加密导出 * * @param workbook workbook * @param fileName fileName * @param response response * @param password password */ public static void encryptExport(final Workbook workbook, String fileName, HttpServletResponse response, final String password) { if (workbook instanceof HSSFWorkbook) { throw new IllegalArgumentException("Document encryption for.xls is not supported"); } Path path = null; try { String suffix = Constants.XLSX; path = TempFileOperator.createTempFile("encrypt_temp", suffix); workbook.write(Files.newOutputStream(path)); final POIFSFileSystem fs = new POIFSFileSystem(); final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard); final Encryptor enc = info.getEncryptor(); enc.confirmPassword(password); try (OPCPackage opc = OPCPackage.open(path.toFile(), PackageAccess.READ_WRITE); OutputStream os = enc.getDataStream(fs)) { opc.save(os); } if (!fileName.endsWith(suffix)) { fileName += suffix; } response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); setAttachmentConfig(fileName, response); fs.writeFilesystem(response.getOutputStream()); } catch (IOException | InvalidFormatException | GeneralSecurityException e) { throw new RuntimeException(e); } finally { clear(workbook); TempFileOperator.deleteTempFile(path); } }
Example #7
Source File: FileExportUtil.java From myexcel with Apache License 2.0 | 5 votes |
/** * 加密导出 * * @param workbook workbook * @param file file * @param password password * @throws Exception Exception */ public static void encryptExport(final Workbook workbook, File file, final String password) throws Exception { if (workbook instanceof HSSFWorkbook) { throw new IllegalArgumentException("Document encryption for.xls is not supported"); } String suffix = Constants.XLSX; if (!file.getName().endsWith(suffix)) { file = Paths.get(file.getAbsolutePath() + suffix).toFile(); } try (FileOutputStream fos = new FileOutputStream(file)) { workbook.write(fos); if (workbook instanceof SXSSFWorkbook) { ((SXSSFWorkbook) workbook).dispose(); } final POIFSFileSystem fs = new POIFSFileSystem(); final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard); final Encryptor enc = info.getEncryptor(); enc.confirmPassword(password); try (OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE); OutputStream os = enc.getDataStream(fs)) { opc.save(os); } try (FileOutputStream fileOutputStream = new FileOutputStream(file)) { fs.writeFilesystem(fileOutputStream); } } finally { workbook.close(); } }
Example #8
Source File: MSExcelOOXMLSignUtil.java From hadoopoffice with Apache License 2.0 | 5 votes |
private void signEncryptedPackage(InputStream tmpFileInputStream, SignatureConfig sc, String password) throws IOException, InvalidFormatException, FormatNotUnderstoodException, XMLSignatureException, MarshalException { POIFSFileSystem poifsTemp = new POIFSFileSystem(tmpFileInputStream); EncryptionInfo info = new EncryptionInfo(poifsTemp); Decryptor d = Decryptor.getInstance(info); try { if (!d.verifyPassword(password)) { throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing. Invalid password"); } // signing OPCPackage pkg = OPCPackage.open(d.getDataStream(poifsTemp)); sc.setOpcPackage(pkg); SignatureInfo si = new SignatureInfo(); si.setSignatureConfig(sc); si.confirmSignature(); // encrypt again Encryptor enc = info.getEncryptor(); enc.confirmPassword(password); POIFSFileSystem poifs = new POIFSFileSystem(); OutputStream os = enc.getDataStream(poifs); pkg.save(os); pkg.close(); if (os!=null) { os.close(); } poifs.writeFilesystem(this.finalOutputStream); if (poifs!=null) { poifs.close(); } if (poifsTemp!=null) { poifsTemp.close(); } } catch (GeneralSecurityException e) { LOG.error(e); throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing."); } }
Example #9
Source File: POIDocument.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Writes out the standard Document Information Properties (HPSF) * @param outFS the NPOIFSFileSystem to write the properties into * @param writtenEntries a list of POIFS entries to add the property names too * * @throws IOException if an error when writing to the * {@link NPOIFSFileSystem} occurs */ protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException { EncryptionInfo ei = getEncryptionInfo(); final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted()); NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : outFS; SummaryInformation si = getSummaryInformation(); if (si != null) { writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, si, fs); if(writtenEntries != null) { writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME); } } DocumentSummaryInformation dsi = getDocumentSummaryInformation(); if (dsi != null) { writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, fs); if(writtenEntries != null) { writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME); } } if (!encryptProps) { return; } // create empty document summary dsi = PropertySetFactory.newDocumentSummaryInformation(); writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS); // remove summary, if previously available if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) { outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete(); } Encryptor encGen = ei.getEncryptor(); if (!(encGen instanceof CryptoAPIEncryptor)) { throw new EncryptedDocumentException("Using "+ei.getEncryptionMode()+" encryption. Only CryptoAPI encryption supports encrypted property sets!"); } CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen; try { enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs); } catch (GeneralSecurityException e) { throw new IOException(e); } finally { fs.close(); } }
Example #10
Source File: HSSFWorkbook.java From lams with GNU General Public License v2.0 | 4 votes |
@SuppressWarnings("resource") protected void encryptBytes(byte buf[]) { EncryptionInfo ei = getEncryptionInfo(); if (ei == null) { return; } Encryptor enc = ei.getEncryptor(); int initialOffset = 0; LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0); // NOSONAR LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0); // NOSONAR enc.setChunkSize(Biff8DecryptingStream.RC4_REKEYING_INTERVAL); byte tmp[] = new byte[1024]; try { ChunkedCipherOutputStream os = enc.getDataStream(leos, initialOffset); int totalBytes = 0; while (totalBytes < buf.length) { plain.read(tmp, 0, 4); final int sid = LittleEndian.getUShort(tmp, 0); final int len = LittleEndian.getUShort(tmp, 2); boolean isPlain = Biff8DecryptingStream.isNeverEncryptedRecord(sid); os.setNextRecordSize(len, isPlain); os.writePlain(tmp, 0, 4); if (sid == BoundSheetRecord.sid) { // special case for the field_1_position_of_BOF (=lbPlyPos) field of // the BoundSheet8 record which must be unencrypted byte bsrBuf[] = new byte[len]; plain.readFully(bsrBuf); os.writePlain(bsrBuf, 0, 4); os.write(bsrBuf, 4, len-4); } else { int todo = len; while (todo > 0) { int nextLen = Math.min(todo, tmp.length); plain.readFully(tmp, 0, nextLen); if (isPlain) { os.writePlain(tmp, 0, nextLen); } else { os.write(tmp, 0, nextLen); } todo -= nextLen; } } totalBytes += 4 + len; } os.close(); } catch (Exception e) { throw new EncryptedDocumentException(e); } }
Example #11
Source File: MSExcelWriter.java From hadoopoffice with Apache License 2.0 | 4 votes |
private void finalizeWriteEncryptedXSSF() throws IOException{ if (this.encryptAlgorithmCipher==null) { LOG.error("No encryption algorithm specified"); return; } else if (this.hashAlgorithmCipher==null) { LOG.error("No hash algorithm specified"); return; } else if (this.encryptionModeCipher==null) { LOG.error("No encryption mode specified"); return; } else if (this.chainModeCipher==null) { LOG.error("No chain mode specified"); return; } OutputStream os = null; try { EncryptionInfo info = new EncryptionInfo(this.encryptionModeCipher, this.encryptAlgorithmCipher, this.hashAlgorithmCipher, -1, -1, this.chainModeCipher); Encryptor enc = info.getEncryptor(); enc.confirmPassword(this.howc.getPassword()); try { os = enc.getDataStream(ooxmlDocumentFileSystem); if (os!=null) { this.currentWorkbook.write(os); } if (os!=null) { os.close(); } } catch (GeneralSecurityException e) { LOG.error(e); } OutputStream theOS=this.oStream; if (this.signUtil!=null) { theOS= this.signUtil.getTempOutputStream(); } ooxmlDocumentFileSystem.writeFilesystem(theOS); } finally { if ((this.oStream!=null) && (this.signUtil==null)) { // if we need to sign it we close it later after signing this.oStream.close(); } } }