Search in sources :

Example 66 with NPOIFSFileSystem

use of org.apache.poi.poifs.filesystem.NPOIFSFileSystem in project poi by apache.

the class TestEncryptor method standardEncryption.

@Test
public void standardEncryption() throws Exception {
    File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx");
    String pass = "solrcell";
    NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);
    // Check the encryption details
    EncryptionInfo infoExpected = new EncryptionInfo(nfs);
    Decryptor d = Decryptor.getInstance(infoExpected);
    boolean passed = d.verifyPassword(pass);
    assertTrue("Unable to process: document is encrypted", passed);
    // extract the payload
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream is = d.getDataStream(nfs);
    IOUtils.copy(is, bos);
    is.close();
    nfs.close();
    byte[] payloadExpected = bos.toByteArray();
    // check that same verifier/salt lead to same hashes
    byte[] verifierSaltExpected = infoExpected.getVerifier().getSalt();
    byte[] verifierExpected = d.getVerifier();
    byte[] keySpec = d.getSecretKey().getEncoded();
    byte[] keySalt = infoExpected.getHeader().getKeySalt();
    EncryptionInfo infoActual = new EncryptionInfo(EncryptionMode.standard, infoExpected.getVerifier().getCipherAlgorithm(), infoExpected.getVerifier().getHashAlgorithm(), infoExpected.getHeader().getKeySize(), infoExpected.getHeader().getBlockSize(), infoExpected.getVerifier().getChainingMode());
    Encryptor e = Encryptor.getInstance(infoActual);
    e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);
    assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifier(), infoActual.getVerifier().getEncryptedVerifier());
    assertArrayEquals(infoExpected.getVerifier().getEncryptedVerifierHash(), infoActual.getVerifier().getEncryptedVerifierHash());
    // now we use a newly generated salt/verifier and check
    // if the file content is still the same 
    infoActual = new EncryptionInfo(EncryptionMode.standard, infoExpected.getVerifier().getCipherAlgorithm(), infoExpected.getVerifier().getHashAlgorithm(), infoExpected.getHeader().getKeySize(), infoExpected.getHeader().getBlockSize(), infoExpected.getVerifier().getChainingMode());
    e = Encryptor.getInstance(infoActual);
    e.confirmPassword(pass);
    POIFSFileSystem fs = new POIFSFileSystem();
    OutputStream os = e.getDataStream(fs);
    IOUtils.copy(new ByteArrayInputStream(payloadExpected), os);
    os.close();
    bos.reset();
    fs.writeFilesystem(bos);
    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    // FileOutputStream fos = new FileOutputStream("encrypted.docx");
    // IOUtils.copy(bis, fos);
    // fos.close();
    // bis.reset();
    nfs = new NPOIFSFileSystem(bis);
    infoExpected = new EncryptionInfo(nfs);
    d = Decryptor.getInstance(infoExpected);
    passed = d.verifyPassword(pass);
    assertTrue("Unable to process: document is encrypted", passed);
    bos.reset();
    is = d.getDataStream(nfs);
    IOUtils.copy(is, bos);
    is.close();
    nfs.close();
    byte[] payloadActual = bos.toByteArray();
    assertArrayEquals(payloadExpected, payloadActual);
}
Also used : AgileDecryptor(org.apache.poi.poifs.crypt.agile.AgileDecryptor) ByteArrayInputStream(java.io.ByteArrayInputStream) BoundedInputStream(org.apache.poi.util.BoundedInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) ByteArrayInputStream(java.io.ByteArrayInputStream) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) TempFile(org.apache.poi.util.TempFile) File(java.io.File) Test(org.junit.Test)

Example 67 with NPOIFSFileSystem

use of org.apache.poi.poifs.filesystem.NPOIFSFileSystem in project poi by apache.

the class TestEncryptor method bug60320CustomEncrypt.

/*
     * this test simulates the generation of bugs 60320 sample file
     * as the padding bytes of the EncryptedPackage stream are random or in POIs case PKCS5-padded
     * one would need to mock those bytes to get the same hmacValues - see diff below
     *
     * this use-case is experimental - for the time being the setters of the encryption classes
     * are spreaded between two packages and are protected - so you would need to violate
     * the packages rules and provide a helper class in the *poifs.crypt package-namespace.
     * the default way of defining the encryption settings is via the EncryptionInfo class
     */
@Test
public void bug60320CustomEncrypt() throws Exception {
    int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
    Assume.assumeTrue("Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256", maxKeyLen == 2147483647);
    // --- src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java  (revision 1766745)
    // +++ src/java/org/apache/poi/poifs/crypt/ChunkedCipherOutputStream.java  (working copy)
    // @@ -208,6 +208,13 @@
    //      protected int invokeCipher(int posInChunk, boolean doFinal) throws GeneralSecurityException {
    //          byte plain[] = (_plainByteFlags.isEmpty()) ? null : _chunk.clone();
    //  
    // +        if (posInChunk < 4096) {
    // +            _cipher.update(_chunk, 0, posInChunk, _chunk);
    // +            byte bla[] = { (byte)0x7A,(byte)0x0F,(byte)0x27,(byte)0xF0,(byte)0x17,(byte)0x6E,(byte)0x77,(byte)0x05,(byte)0xB9,(byte)0xDA,(byte)0x49,(byte)0xF9,(byte)0xD7,(byte)0x8E,(byte)0x03,(byte)0x1D };
    // +            System.arraycopy(bla, 0, _chunk, posInChunk-2, bla.length);
    // +            return posInChunk-2+bla.length;
    // +        }
    // +        
    //          int ciLen = (doFinal)
    //              ? _cipher.doFinal(_chunk, 0, posInChunk, _chunk)
    //              : _cipher.update(_chunk, 0, posInChunk, _chunk);
    //
    //      --- src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (revision 1766745)
    //      +++ src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java (working copy)
    //      
    //      @@ -300,7 +297,7 @@
    //      protected static Cipher initCipherForBlock(Cipher existing, int block, boolean lastChunk, EncryptionInfo encryptionInfo, SecretKey skey, int encryptionMode)
    //      throws GeneralSecurityException {
    //          EncryptionHeader header = encryptionInfo.getHeader();
    // -        String padding = (lastChunk ? "PKCS5Padding" : "NoPadding");
    // +        String padding = "NoPadding"; // (lastChunk ? "PKCS5Padding" : "NoPadding");
    //          if (existing == null || !existing.getAlgorithm().endsWith(padding)) {
    //              existing = getCipher(skey, header.getCipherAlgorithm(), header.getChainingMode(), header.getKeySalt(), encryptionMode, padding);
    //          }
    InputStream is = POIDataSamples.getPOIFSInstance().openResourceAsStream("60320-protected.xlsx");
    POIFSFileSystem fsOrig = new POIFSFileSystem(is);
    is.close();
    EncryptionInfo infoOrig = new EncryptionInfo(fsOrig);
    Decryptor decOrig = infoOrig.getDecryptor();
    boolean b = decOrig.verifyPassword("Test001!!");
    assertTrue(b);
    InputStream decIn = decOrig.getDataStream(fsOrig);
    byte[] zipInput = IOUtils.toByteArray(decIn);
    decIn.close();
    InputStream epOrig = fsOrig.getRoot().createDocumentInputStream("EncryptedPackage");
    // ignore the 16 padding bytes
    byte[] epOrigBytes = IOUtils.toByteArray(epOrig, 9400);
    epOrig.close();
    EncryptionInfo eiNew = new EncryptionInfo(EncryptionMode.agile);
    AgileEncryptionHeader aehHeader = (AgileEncryptionHeader) eiNew.getHeader();
    aehHeader.setCipherAlgorithm(CipherAlgorithm.aes128);
    aehHeader.setHashAlgorithm(HashAlgorithm.sha1);
    AgileEncryptionVerifier aehVerifier = (AgileEncryptionVerifier) eiNew.getVerifier();
    // this cast might look strange - if the setters would be public, it will become obsolete
    // see http://stackoverflow.com/questions/5637650/overriding-protected-methods-in-java
    ((EncryptionVerifier) aehVerifier).setCipherAlgorithm(CipherAlgorithm.aes256);
    aehVerifier.setHashAlgorithm(HashAlgorithm.sha512);
    Encryptor enc = eiNew.getEncryptor();
    enc.confirmPassword("Test001!!", infoOrig.getDecryptor().getSecretKey().getEncoded(), infoOrig.getHeader().getKeySalt(), infoOrig.getDecryptor().getVerifier(), infoOrig.getVerifier().getSalt(), infoOrig.getDecryptor().getIntegrityHmacKey());
    NPOIFSFileSystem fsNew = new NPOIFSFileSystem();
    OutputStream os = enc.getDataStream(fsNew);
    os.write(zipInput);
    os.close();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    fsNew.writeFilesystem(bos);
    fsNew.close();
    NPOIFSFileSystem fsReload = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
    InputStream epReload = fsReload.getRoot().createDocumentInputStream("EncryptedPackage");
    byte[] epNewBytes = IOUtils.toByteArray(epReload, 9400);
    epReload.close();
    assertArrayEquals(epOrigBytes, epNewBytes);
    EncryptionInfo infoReload = new EncryptionInfo(fsOrig);
    Decryptor decReload = infoReload.getDecryptor();
    b = decReload.verifyPassword("Test001!!");
    assertTrue(b);
    AgileEncryptionHeader aehOrig = (AgileEncryptionHeader) infoOrig.getHeader();
    AgileEncryptionHeader aehReload = (AgileEncryptionHeader) infoReload.getHeader();
    assertEquals(aehOrig.getBlockSize(), aehReload.getBlockSize());
    assertEquals(aehOrig.getChainingMode(), aehReload.getChainingMode());
    assertEquals(aehOrig.getCipherAlgorithm(), aehReload.getCipherAlgorithm());
    assertEquals(aehOrig.getCipherProvider(), aehReload.getCipherProvider());
    assertEquals(aehOrig.getCspName(), aehReload.getCspName());
    assertArrayEquals(aehOrig.getEncryptedHmacKey(), aehReload.getEncryptedHmacKey());
    // this only works, when the paddings are mocked to be the same ...
    // assertArrayEquals(aehOrig.getEncryptedHmacValue(), aehReload.getEncryptedHmacValue());
    assertEquals(aehOrig.getFlags(), aehReload.getFlags());
    assertEquals(aehOrig.getHashAlgorithm(), aehReload.getHashAlgorithm());
    assertArrayEquals(aehOrig.getKeySalt(), aehReload.getKeySalt());
    assertEquals(aehOrig.getKeySize(), aehReload.getKeySize());
    AgileEncryptionVerifier aevOrig = (AgileEncryptionVerifier) infoOrig.getVerifier();
    AgileEncryptionVerifier aevReload = (AgileEncryptionVerifier) infoReload.getVerifier();
    assertEquals(aevOrig.getBlockSize(), aevReload.getBlockSize());
    assertEquals(aevOrig.getChainingMode(), aevReload.getChainingMode());
    assertEquals(aevOrig.getCipherAlgorithm(), aevReload.getCipherAlgorithm());
    assertArrayEquals(aevOrig.getEncryptedKey(), aevReload.getEncryptedKey());
    assertArrayEquals(aevOrig.getEncryptedVerifier(), aevReload.getEncryptedVerifier());
    assertArrayEquals(aevOrig.getEncryptedVerifierHash(), aevReload.getEncryptedVerifierHash());
    assertEquals(aevOrig.getHashAlgorithm(), aevReload.getHashAlgorithm());
    assertEquals(aevOrig.getKeySize(), aevReload.getKeySize());
    assertArrayEquals(aevOrig.getSalt(), aevReload.getSalt());
    assertEquals(aevOrig.getSpinCount(), aevReload.getSpinCount());
    AgileDecryptor adOrig = (AgileDecryptor) infoOrig.getDecryptor();
    AgileDecryptor adReload = (AgileDecryptor) infoReload.getDecryptor();
    assertArrayEquals(adOrig.getIntegrityHmacKey(), adReload.getIntegrityHmacKey());
    // doesn't work without mocking ... see above
    // assertArrayEquals(adOrig.getIntegrityHmacValue(), adReload.getIntegrityHmacValue());
    assertArrayEquals(adOrig.getSecretKey().getEncoded(), adReload.getSecretKey().getEncoded());
    assertArrayEquals(adOrig.getVerifier(), adReload.getVerifier());
    fsReload.close();
}
Also used : AgileEncryptionVerifier(org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier) AgileDecryptor(org.apache.poi.poifs.crypt.agile.AgileDecryptor) ByteArrayInputStream(java.io.ByteArrayInputStream) BoundedInputStream(org.apache.poi.util.BoundedInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) AgileEncryptionVerifier(org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AgileEncryptionHeader(org.apache.poi.poifs.crypt.agile.AgileEncryptionHeader) NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) ByteArrayInputStream(java.io.ByteArrayInputStream) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) AgileDecryptor(org.apache.poi.poifs.crypt.agile.AgileDecryptor) Test(org.junit.Test)

Example 68 with NPOIFSFileSystem

use of org.apache.poi.poifs.filesystem.NPOIFSFileSystem in project poi by apache.

the class TestDecryptor method bug57080.

@Test
public void bug57080() throws Exception {
    // the test file contains a wrong ole entry size, produced by extenxls
    // the fix limits the available size and tries to read all entries 
    File f = POIDataSamples.getPOIFSInstance().getFile("extenxls_pwd123.xlsx");
    NPOIFSFileSystem fs = new NPOIFSFileSystem(f, true);
    EncryptionInfo info = new EncryptionInfo(fs);
    Decryptor d = Decryptor.getInstance(info);
    d.verifyPassword("pwd123");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ZipInputStream zis = new ZipInputStream(d.getDataStream(fs));
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        bos.reset();
        IOUtils.copy(zis, bos);
        assertEquals(ze.getSize(), bos.size());
    }
    zis.close();
    fs.close();
}
Also used : NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) ZipInputStream(java.util.zip.ZipInputStream) ZipEntry(java.util.zip.ZipEntry) ByteArrayOutputStream(java.io.ByteArrayOutputStream) File(java.io.File) Test(org.junit.Test)

Example 69 with NPOIFSFileSystem

use of org.apache.poi.poifs.filesystem.NPOIFSFileSystem in project poi by apache.

the class TestEncryptor method inPlaceRewrite.

@Test
@Ignore
public void inPlaceRewrite() throws Exception {
    File f = TempFile.createTempFile("protected_agile", ".docx");
    // File f = new File("protected_agile.docx");
    FileOutputStream fos = new FileOutputStream(f);
    InputStream fis = POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx");
    IOUtils.copy(fis, fos);
    fis.close();
    fos.close();
    NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false);
    // 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 ;)
    InputStream docIS = d.getDataStream(fs);
    XWPFDocument docx = new XWPFDocument(docIS);
    docx.getParagraphArray(0).insertNewRun(0).setText("POI was here! All your base are belong to us!");
    docx.getParagraphArray(0).insertNewRun(1).addBreak();
    // and encrypt it again
    Encryptor e = encInfo.getEncryptor();
    e.confirmPassword("AYBABTU");
    docx.write(e.getDataStream(fs));
    docx.close();
    docIS.close();
    docx.close();
    fs.close();
}
Also used : NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) AgileDecryptor(org.apache.poi.poifs.crypt.agile.AgileDecryptor) ByteArrayInputStream(java.io.ByteArrayInputStream) BoundedInputStream(org.apache.poi.util.BoundedInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) TempFile(org.apache.poi.util.TempFile) File(java.io.File) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 70 with NPOIFSFileSystem

use of org.apache.poi.poifs.filesystem.NPOIFSFileSystem in project poi by apache.

the class TestXWPFBugs method bug53475NoCSPName.

/**
     * A word document that's encrypted with non-standard
     * Encryption options, and no cspname section. See bug 53475
     */
@Test
public void bug53475NoCSPName() throws Exception {
    File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx");
    NPOIFSFileSystem filesystem = new NPOIFSFileSystem(file, true);
    // Check the encryption details
    EncryptionInfo info = new EncryptionInfo(filesystem);
    assertEquals(128, info.getHeader().getKeySize());
    assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm());
    assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());
    // Check it can be decoded
    Decryptor d = Decryptor.getInstance(info);
    assertTrue("Unable to process: document is encrypted", d.verifyPassword("solrcell"));
    // Check we can read the word document in that
    InputStream dataStream = d.getDataStream(filesystem);
    OPCPackage opc = OPCPackage.open(dataStream);
    XWPFDocument doc = new XWPFDocument(opc);
    XWPFWordExtractor ex = new XWPFWordExtractor(doc);
    String text = ex.getText();
    assertNotNull(text);
    assertEquals("This is password protected Word document.", text.trim());
    ex.close();
    filesystem.close();
}
Also used : NPOIFSFileSystem(org.apache.poi.poifs.filesystem.NPOIFSFileSystem) Decryptor(org.apache.poi.poifs.crypt.Decryptor) EncryptionInfo(org.apache.poi.poifs.crypt.EncryptionInfo) InputStream(java.io.InputStream) XWPFWordExtractor(org.apache.poi.xwpf.extractor.XWPFWordExtractor) XWPFDocument(org.apache.poi.xwpf.usermodel.XWPFDocument) File(java.io.File) ZipFile(java.util.zip.ZipFile) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) Test(org.junit.Test)

Aggregations

NPOIFSFileSystem (org.apache.poi.poifs.filesystem.NPOIFSFileSystem)101 Test (org.junit.Test)57 File (java.io.File)35 InputStream (java.io.InputStream)26 ByteArrayInputStream (java.io.ByteArrayInputStream)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)14 MAPIMessage (org.apache.poi.hsmf.MAPIMessage)14 FileOutputStream (java.io.FileOutputStream)12 TempFile (org.apache.poi.util.TempFile)12 FileInputStream (java.io.FileInputStream)11 OPOIFSFileSystem (org.apache.poi.poifs.filesystem.OPOIFSFileSystem)10 POIFSFileSystem (org.apache.poi.poifs.filesystem.POIFSFileSystem)10 DocumentSummaryInformation (org.apache.poi.hpsf.DocumentSummaryInformation)9 DirectoryNode (org.apache.poi.poifs.filesystem.DirectoryNode)9 IOException (java.io.IOException)8 OutputStream (java.io.OutputStream)8 SummaryInformation (org.apache.poi.hpsf.SummaryInformation)7 TikaInputStream (org.apache.tika.io.TikaInputStream)6 AgileDecryptor (org.apache.poi.poifs.crypt.agile.AgileDecryptor)5 DirectoryEntry (org.apache.poi.poifs.filesystem.DirectoryEntry)5