Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.apache.poi.xslf.usermodel;
- import static org.junit.Assert.assertTrue;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Arrays;
- import org.apache.poi.POIDataSamples;
- import org.apache.poi.poifs.common.POIFSConstants;
- import org.apache.poi.poifs.crypt.Decryptor;
- import org.apache.poi.poifs.crypt.EncryptionInfo;
- import org.apache.poi.poifs.crypt.EncryptionMode;
- import org.apache.poi.poifs.crypt.Encryptor;
- import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
- import org.apache.poi.poifs.filesystem.POIFSFileSystem;
- import org.apache.poi.xwpf.usermodel.XWPFDocument;
- import org.junit.Test;
- public class TestMisc {
- @Test
- public void protectedRewrite() throws Exception {
- File docs[] = {
- POIDataSamples.getDocumentInstance().getFile("52288.docx"),
- POIDataSamples.getPOIFSInstance().getFile("protected_agile.docx"),
- };
- for (File doc : docs) {
- if (isEncrypted(doc)) {
- NPOIFSFileSystem fs = new NPOIFSFileSystem(doc, true);
- // decrypt the protected file - in this case it was encrypted with the default password
- EncryptionInfo encInfo = new EncryptionInfo(fs);
- Decryptor d = encInfo.getDecryptor();
- boolean b = d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
- assertTrue(b);
- // do some strange things with it
- XWPFDocument docx = new XWPFDocument(d.getDataStream(fs));
- docx.getParagraphArray(0).insertNewRun(0).setText("Ajeet was here! All your base are belong to us!");
- docx.getParagraphArray(0).insertNewRun(1).addBreak();
- // in-place write of the original npoifs doesn't work, so using a new POIFS for now
- fs.close();
- // and encrypt it again
- POIFSFileSystem fs2 = new POIFSFileSystem();
- encInfo = new EncryptionInfo(fs2, EncryptionMode.agile);
- Encryptor e = encInfo.getEncryptor();
- e.confirmPassword("AYBABTU");
- docx.write(e.getDataStream(fs2));
- FileOutputStream fos = new FileOutputStream(new File(doc.getName()));
- fs2.writeFilesystem(fos);
- fos.close();
- } else {
- System.out.println(doc.getName()+" is without encryption");
- }
- }
- }
- public static boolean isEncrypted(File file) throws IOException {
- FileInputStream fis = new FileInputStream(file);
- byte buf[] = new byte[4];
- fis.read(buf);
- fis.close();
- if (Arrays.equals(buf, POIFSConstants.OOXML_FILE_HEADER)) {
- // plain ooxml
- return false;
- }
- NPOIFSFileSystem poifs = new NPOIFSFileSystem(file);
- boolean hasEncInf = poifs.getRoot().hasEntry("EncryptionInfo");
- poifs.close();
- return hasEncInf;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement