]> source.dussan.org Git - poi.git/commitdiff
Patch for Bug/Enhancement 55818 - add encryption support
authorAndreas Beeker <kiwiwings@apache.org>
Tue, 24 Dec 2013 23:13:21 +0000 (23:13 +0000)
committerAndreas Beeker <kiwiwings@apache.org>
Tue, 24 Dec 2013 23:13:21 +0000 (23:13 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1553336 13f79535-47bb-0310-9956-ffa450edef68

48 files changed:
.classpath
build.xml
src/java/org/apache/poi/EncryptedDocumentException.java
src/java/org/apache/poi/poifs/crypt/AgileDecryptor.java [deleted file]
src/java/org/apache/poi/poifs/crypt/ChainingMode.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/CipherAlgorithm.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/CipherProvider.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/DataSpaceMapUtils.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/Decryptor.java
src/java/org/apache/poi/poifs/crypt/EcmaDecryptor.java [deleted file]
src/java/org/apache/poi/poifs/crypt/EncryptionHeader.java
src/java/org/apache/poi/poifs/crypt/EncryptionInfo.java
src/java/org/apache/poi/poifs/crypt/EncryptionInfoBuilder.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/EncryptionMode.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/EncryptionVerifier.java
src/java/org/apache/poi/poifs/crypt/Encryptor.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/HashAlgorithm.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/package.html [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/EncryptionRecord.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionHeader.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionInfoBuilder.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionVerifier.java [new file with mode: 0644]
src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/POIXMLException.java
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionHeader.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionInfoBuilder.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionVerifier.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java [new file with mode: 0644]
src/ooxml/java/org/apache/poi/util/OOXMLLite.java
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd [new file with mode: 0644]
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig [new file with mode: 0644]
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd [new file with mode: 0644]
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig [new file with mode: 0644]
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd [new file with mode: 0644]
src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java [new file with mode: 0644]
src/ooxml/testcases/org/apache/poi/xwpf/TestXWPFBugs.java
src/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java [deleted file]
src/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java [deleted file]
src/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java [deleted file]

index facc548d7000e9e6bb034f7081a51486e950cfe7..d3cabd61b7f57e38f92d9b195a547018a79caac9 100644 (file)
@@ -24,6 +24,7 @@
        <classpathentry kind="lib" path="lib/hamcrest-core-1.3.jar"/>
        <classpathentry kind="lib" path="lib/junit-4.11.jar"/>
        <classpathentry kind="lib" path="ooxml-lib/ooxml-schemas-1.1.jar" sourcepath="ooxml-lib/ooxml-schemas-src-1.1.jar"/>
+       <classpathentry kind="lib" path="ooxml-lib/ooxml-encryption-1.1.jar" sourcepath="ooxml-lib/ooxml-encryption-src-1.1.jar"/>
        <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
        <classpathentry kind="output" path="build/eclipse"/>
 </classpath>
index f461bd416846806ae9b35f20b934d7c949d5204e..f7fed23227a77f037ca68644a8684a5d3b21bf5a 100644 (file)
--- a/build.xml
+++ b/build.xml
@@ -116,6 +116,7 @@ under the License.
     <property name="ooxml.output.test.dir" location="build/ooxml-test-classes"/>
     <property name="ooxml.testokfile" location="build/ooxml-testokfile.txt"/>
     <property name="ooxml.lite.output.dir" location="build/ooxml-lite-classes"/>
+    <property name="ooxml.encryption.xsd.dir" location="src/ooxml/resources/org/apache/poi/poifs/crypt"/>
 
     <!-- Excelant: -->
     <property name="excelant.resource.dir" value="src/excelant/resources"/>
@@ -167,6 +168,11 @@ under the License.
     <property name="ooxml.xsds.src.jar" location="${ooxml.lib}/ooxml-schemas-src-1.1.jar"/>
     <property name="ooxml.xsds.jar" location="${ooxml.lib}/ooxml-schemas-1.1.jar"/>
 
+    <property name="ooxml.encryption.src.dir" location="build/ooxml-encryption-src"/>
+    <property name="ooxml.encryption.src.jar" location="${ooxml.lib}/ooxml-encryption-src-1.1.jar"/>
+    <property name="ooxml.encryption.jar" location="${ooxml.lib}/ooxml-encryption-1.1.jar"/>
+
+
     <property name="maven.ooxml.xsds.version.id" value="1.0"/>
     <property name="maven.ooxml.xsds.jar" value="ooxml-schemas-${maven.ooxml.xsds.version.id}.jar"/>
 
@@ -210,6 +216,7 @@ under the License.
         <path refid="main.classpath"/>
         <pathelement location="${main.output.dir}"/>
         <pathelement location="${scratchpad.output.dir}"/>
+        <pathelement location="${ooxml.encryption.jar}"/>
     </path>
 
     <path id="test.classpath">
@@ -436,9 +443,13 @@ under the License.
     <target name="check-compiled-ooxml-xsds" depends="fetch-ooxml-xsds">
         <condition property="ooxml-compiled-xsds.present">
             <or>
-                <and>
-                    <available file="${ooxml.xsds.jar}"/>
-                </and>
+                <available file="${ooxml.xsds.jar}"/>
+                <isset property="disconnected"/>
+            </or>
+        </condition>
+        <condition property="ooxml-compiled-encryption-xsds.present">
+            <or>
+                <available file="${ooxml.encryption.jar}"/>
                 <isset property="disconnected"/>
             </or>
         </condition>
@@ -485,6 +496,40 @@ under the License.
                 />
     </target>
 
+    <target name="compile-ooxml-encryption-xsds" unless="ooxml-compiled-encryption-xsds.present"
+            depends="check-jars,fetch-jars,check-compiled-ooxml-xsds"
+            description="Compiles the OOXML encryption xsd files into XmlBeans">
+        <taskdef name="xmlbean"
+                 classname="org.apache.xmlbeans.impl.tool.XMLBean"
+                 classpath="${ooxml.xmlbeans.jar}:${ooxml.jsr173.jar}"/>
+
+        <!-- We need a fair amount of memory to compile the xml schema, -->
+        <!--  but limit it in case it goes wrong! -->
+        <!-- Pick the right amount based on 32 vs 64 bit jvm -->
+        <condition property="ooxml.memory" value="768m" else="512m">
+           <equals arg1="${sun.arch.data.model}" arg2="64" />
+        </condition>
+
+        <xmlbean
+                schema="${ooxml.encryption.xsd.dir}"
+                srcgendir="${ooxml.encryption.src.dir}"
+                optimize="yes"
+                destfile="${ooxml.encryption.jar}"
+                javasource="1.5"
+                failonerror="true"
+                fork="true"
+                memoryMaximumSize="${ooxml.memory}"
+                >
+            <classpath refid="ooxml.classpath"/>
+        </xmlbean>
+
+        <!-- Now make a jar of the schema sources -->
+        <jar
+                basedir="${ooxml.encryption.src.dir}"
+                destfile="${ooxml.encryption.src.jar}"
+                />
+    </target>
+
     <target name="compile" depends="init, compile-main,
             compile-scratchpad, compile-examples, compile-excelant"
             description="Compiles the POI main classes, scratchpad and examples"/>
@@ -571,7 +616,7 @@ under the License.
         </copy>
     </target>
 
-    <target name="compile-ooxml" depends="compile-main,compile-scratchpad,compile-ooxml-xsds">
+    <target name="compile-ooxml" depends="compile-main,compile-scratchpad,compile-ooxml-xsds,compile-ooxml-encryption-xsds">
         <javac target="${jdk.version.class}"
                source="${jdk.version.source}"
                destdir="${ooxml.output.dir}"
@@ -853,12 +898,23 @@ under the License.
     </target>
 
     <target name="compile-ooxml-lite" depends="compile-ooxml">
+        <property name="ooxml.lite-merged.dir" location="build/ooxml-lite-merged"/>
+        <mkdir dir="${ooxml.lite-merged.dir}"/>
+
+       <jar destfile="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar">
+               <zipfileset includes="**/*" src="${ooxml.xsds.jar}"/>
+               <zipfileset includes="**/*" src="${ooxml.encryption.jar}"/>
+        </jar>
+       
         <java classname="org.apache.poi.util.OOXMLLite" fork="yes">
+               <classpath>
+                       <pathelement path="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
+               </classpath>
             <classpath refid="test.ooxml.classpath"/>
             <syspropertyset refid="junit.properties"/>
             <jvmarg value="${poi.test.locale}"/>
             <arg value="-ooxml"/>
-            <arg value="${ooxml.xsds.jar}"/>
+            <arg value="${ooxml.lite-merged.dir}/ooxml-lite-merged.jar"/>
             <arg value="-test"/>
             <arg value="${ooxml.output.test.dir}"/>
             <arg value="-dest"/>
@@ -951,7 +1007,7 @@ under the License.
             description="Generates the API documentation">
         <javadoc verbose="false" author="true" destdir="${apidocs.report.dir}"
                  windowtitle="POI API Documentation" use="true" version="true" 
-                 maxmemory="256M" additionalparam="-notimestamp">
+                 maxmemory="384M" additionalparam="-notimestamp">
 
             <packageset dir="${main.src}" defaultexcludes="yes">
                 <include name="org/apache/poi/**"/>
index 4922d1c81db976962ce585a2cb909063b6c775cd..12196c80cd214ae109162a1dd869e4b41e95b6ab 100644 (file)
 ==================================================================== */
 package org.apache.poi;
 
+@SuppressWarnings("serial")
 public class EncryptedDocumentException extends IllegalStateException
 {
        public EncryptedDocumentException(String s) {
                super(s);
        }
+
+    public EncryptedDocumentException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    public EncryptedDocumentException(Throwable cause) {
+        super(cause);
+    }
 }
diff --git a/src/java/org/apache/poi/poifs/crypt/AgileDecryptor.java b/src/java/org/apache/poi/poifs/crypt/AgileDecryptor.java
deleted file mode 100644 (file)
index 401049b..0000000
+++ /dev/null
@@ -1,268 +0,0 @@
-/* ====================================================================
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-==================================================================== */
-package org.apache.poi.poifs.crypt;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-
-import javax.crypto.Cipher;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.poifs.filesystem.DocumentInputStream;
-import org.apache.poi.util.LittleEndian;
-
-/**
- * 
- */
-public class AgileDecryptor extends Decryptor {
-
-    private final EncryptionInfo _info;
-    private SecretKey _secretKey;
-    private long _length = -1;
-
-    private static final byte[] kVerifierInputBlock;
-    private static final byte[] kHashedVerifierBlock;
-    private static final byte[] kCryptoKeyBlock;
-
-    static {
-        kVerifierInputBlock =
-            new byte[] { (byte)0xfe, (byte)0xa7, (byte)0xd2, (byte)0x76,
-                         (byte)0x3b, (byte)0x4b, (byte)0x9e, (byte)0x79 };
-        kHashedVerifierBlock =
-            new byte[] { (byte)0xd7, (byte)0xaa, (byte)0x0f, (byte)0x6d,
-                         (byte)0x30, (byte)0x61, (byte)0x34, (byte)0x4e };
-        kCryptoKeyBlock =
-            new byte[] { (byte)0x14, (byte)0x6e, (byte)0x0b, (byte)0xe7,
-                         (byte)0xab, (byte)0xac, (byte)0xd0, (byte)0xd6 };
-    }
-
-    public boolean verifyPassword(String password) throws GeneralSecurityException {
-        EncryptionVerifier verifier = _info.getVerifier();
-        byte[] salt = verifier.getSalt();
-
-        byte[] pwHash = hashPassword(_info, password);
-        byte[] iv = generateIv(salt, null);
-
-        SecretKey skey;
-        skey = new SecretKeySpec(generateKey(pwHash, kVerifierInputBlock), "AES");
-        Cipher cipher = getCipher(skey, iv);
-        byte[] verifierHashInput = cipher.doFinal(verifier.getVerifier());
-
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-        byte[] trimmed = new byte[salt.length];
-        System.arraycopy(verifierHashInput, 0, trimmed, 0, trimmed.length);
-        byte[] hashedVerifier = sha1.digest(trimmed);
-
-        skey = new SecretKeySpec(generateKey(pwHash, kHashedVerifierBlock), "AES");
-        iv = generateIv(salt, null);
-        cipher = getCipher(skey, iv);
-        byte[] verifierHash = cipher.doFinal(verifier.getVerifierHash());
-        trimmed = new byte[hashedVerifier.length];
-        System.arraycopy(verifierHash, 0, trimmed, 0, trimmed.length);
-
-        if (Arrays.equals(trimmed, hashedVerifier)) {
-            skey = new SecretKeySpec(generateKey(pwHash, kCryptoKeyBlock), "AES");
-            iv = generateIv(salt, null);
-            cipher = getCipher(skey, iv);
-            byte[] inter = cipher.doFinal(verifier.getEncryptedKey());
-            byte[] keyspec = new byte[getKeySizeInBytes()];
-            System.arraycopy(inter, 0, keyspec, 0, keyspec.length);
-            _secretKey = new SecretKeySpec(keyspec, "AES");
-            return true;
-        } else {
-            return false;
-        }
-    }
-
-    public InputStream getDataStream(DirectoryNode dir) throws IOException, GeneralSecurityException {
-        DocumentInputStream dis = dir.createDocumentInputStream("EncryptedPackage");
-        _length = dis.readLong();
-        return new ChunkedCipherInputStream(dis, _length);
-    }
-
-    public long getLength(){
-        if(_length == -1) throw new IllegalStateException("EcmaDecryptor.getDataStream() was not called");
-        return _length;
-    }
-
-    protected AgileDecryptor(EncryptionInfo info) {
-        _info = info;
-    }
-
-    private class ChunkedCipherInputStream extends InputStream {
-        private int _lastIndex = 0;
-        private long _pos = 0;
-        private final long _size;
-        private final DocumentInputStream _stream;
-        private byte[] _chunk;
-        private Cipher _cipher;
-
-        public ChunkedCipherInputStream(DocumentInputStream stream, long size)
-            throws GeneralSecurityException {
-            _size = size;
-            _stream = stream;
-            _cipher = getCipher(_secretKey, _info.getHeader().getKeySalt());
-        }
-
-        public int read() throws IOException {
-            byte[] b = new byte[1];
-            if (read(b) == 1)
-                return b[0];
-            return -1;
-        }
-
-        public int read(byte[] b) throws IOException {
-            return read(b, 0, b.length);
-        }
-
-        public int read(byte[] b, int off, int len) throws IOException {
-            int total = 0;
-
-            while (len > 0) {
-                if (_chunk == null) {
-                    try {
-                        _chunk = nextChunk();
-                    } catch (GeneralSecurityException e) {
-                        throw new EncryptedDocumentException(e.getMessage());
-                    }
-                }
-                int count = (int)(4096L - (_pos & 0xfff));
-                count = Math.min(available(), Math.min(count, len));
-                System.arraycopy(_chunk, (int)(_pos & 0xfff), b, off, count);
-                off += count;
-                len -= count;
-                _pos += count;
-                if ((_pos & 0xfff) == 0)
-                    _chunk = null;
-                total += count;
-            }
-
-            return total;
-        }
-
-        public long skip(long n) throws IOException {
-            long start = _pos;
-            long skip = Math.min(available(), n);
-
-            if ((((_pos + skip) ^ start) & ~0xfff) != 0)
-                _chunk = null;
-            _pos += skip;
-            return skip;
-        }
-
-        public int available() throws IOException { return (int)(_size - _pos); }
-        public void close() throws IOException { _stream.close(); }
-        public boolean markSupported() { return false; }
-
-        private byte[] nextChunk() throws GeneralSecurityException, IOException {
-            int index = (int)(_pos >> 12);
-            byte[] blockKey = new byte[4];
-            LittleEndian.putInt(blockKey, 0, index);
-            byte[] iv = generateIv(_info.getHeader().getKeySalt(), blockKey);
-            _cipher.init(Cipher.DECRYPT_MODE, _secretKey, new IvParameterSpec(iv));
-            if (_lastIndex != index)
-                _stream.skip((index - _lastIndex) << 12);
-
-            byte[] block = new byte[Math.min(_stream.available(), 4096)];
-            _stream.readFully(block);
-            _lastIndex = index + 1;
-            return _cipher.doFinal(block);
-        }
-    }
-
-    private Cipher getCipher(SecretKey key, byte[] vec)
-        throws GeneralSecurityException {
-        
-        String name = null;
-        String chain = null;
-
-       EncryptionVerifier verifier = _info.getVerifier();
-        
-        switch (verifier.getAlgorithm()) {
-          case EncryptionHeader.ALGORITHM_AES_128:
-          case EncryptionHeader.ALGORITHM_AES_192:
-          case EncryptionHeader.ALGORITHM_AES_256:
-             name = "AES";
-             break;
-          default:
-             throw new EncryptedDocumentException("Unsupported algorithm");
-        }
-
-        // Ensure the JCE policies files allow for this sized key
-        if (Cipher.getMaxAllowedKeyLength(name) < _info.getHeader().getKeySize()) {
-            throw new EncryptedDocumentException("Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files");
-        }
-        
-        switch (verifier.getCipherMode()) {
-          case EncryptionHeader.MODE_CBC: 
-              chain = "CBC"; 
-              break;
-          case EncryptionHeader.MODE_CFB:
-              chain = "CFB";
-              break;
-          default: 
-              throw new EncryptedDocumentException("Unsupported chain mode");
-        }
-        
-        Cipher cipher = Cipher.getInstance(name + "/" + chain + "/NoPadding");
-        IvParameterSpec iv = new IvParameterSpec(vec);
-        cipher.init(Cipher.DECRYPT_MODE, key, iv);
-        return cipher;
-    }
-
-    private byte[] getBlock(byte[] hash, int size) {
-        byte[] result = new byte[size];
-        Arrays.fill(result, (byte)0x36);
-        System.arraycopy(hash, 0, result, 0, Math.min(result.length, hash.length));
-        return result;
-    }
-
-    private byte[] generateKey(byte[] hash, byte[] blockKey) throws NoSuchAlgorithmException {
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-        sha1.update(hash);
-        byte[] key = sha1.digest(blockKey);
-        return getBlock(key, getKeySizeInBytes());
-    }
-
-    protected byte[] generateIv(byte[] salt, byte[] blockKey)
-        throws NoSuchAlgorithmException {
-
-
-        if (blockKey == null)
-            return getBlock(salt, getBlockSizeInBytes());
-
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-        sha1.update(salt);
-        return getBlock(sha1.digest(blockKey), getBlockSizeInBytes());
-    }
-    
-    protected int getBlockSizeInBytes() {
-       return _info.getHeader().getBlockSize();
-    }
-    
-    protected int getKeySizeInBytes() {
-       return _info.getHeader().getKeySize()/8;
-    }
-}
diff --git a/src/java/org/apache/poi/poifs/crypt/ChainingMode.java b/src/java/org/apache/poi/poifs/crypt/ChainingMode.java
new file mode 100644 (file)
index 0000000..7fccccf
--- /dev/null
@@ -0,0 +1,33 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+public enum ChainingMode {\r
+    // ecb - only for standard encryption\r
+    ecb("ECB", 1),\r
+    cbc("CBC", 2),\r
+    /* Cipher feedback chaining (CFB), with an 8-bit window */\r
+    cfb("CFB8", 3);\r
+\r
+    public final String jceId;\r
+    public final int ecmaId;\r
+    ChainingMode(String jceId, int ecmaId) {\r
+        this.jceId = jceId;\r
+        this.ecmaId = ecmaId;\r
+    }\r
+}
\ No newline at end of file
diff --git a/src/java/org/apache/poi/poifs/crypt/CipherAlgorithm.java b/src/java/org/apache/poi/poifs/crypt/CipherAlgorithm.java
new file mode 100644 (file)
index 0000000..be507a6
--- /dev/null
@@ -0,0 +1,79 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+\r
+public enum CipherAlgorithm {\r
+    // key size for rc4: 0x00000028 - 0x00000080 (inclusive) with 8-bit increments\r
+    // no block size, because its a streaming cipher\r
+    rc4(CipherProvider.rc4,    "RC4", 0x6801, 0x40, new int[]{0x28,0x30,0x38,0x40,0x48,0x50,0x58,0x60,0x68,0x70,0x78,0x80}, -1, 20, "RC4", false),\r
+    // aes has always a block size of 128 - only its keysize may vary\r
+    aes128(CipherProvider.aes, "AES", 0x660E, 128, new int[]{128}, 16, 32, "AES", false),\r
+    aes192(CipherProvider.aes, "AES", 0x660F, 192, new int[]{192}, 16, 32, "AES", false),\r
+    aes256(CipherProvider.aes, "AES", 0x6610, 256, new int[]{256}, 16, 32, "AES", false),\r
+    rc2(null, "RC2", -1, 0x80, new int[]{0x28,0x30,0x38,0x40,0x48,0x50,0x58,0x60,0x68,0x70,0x78,0x80}, 8, 20, "RC2", false),\r
+    des(null, "DES", -1, 64, new int[]{64}, 8/*for 56-bit*/, 32, "DES", false),\r
+    // desx is not supported. Not sure, if it can be simulated by des3 somehow\r
+    des3(null, "DESede", -1, 192, new int[]{192}, 8, 32, "3DES", false),\r
+    // need bouncycastle provider for this one ...\r
+    // see http://stackoverflow.com/questions/4436397/3des-des-encryption-using-the-jce-generating-an-acceptable-key\r
+    des3_112(null, "DESede", -1, 128, new int[]{128}, 8, 32, "3DES_112", true),\r
+    ;\r
+    \r
+    public final CipherProvider provider;\r
+    public final String jceId;\r
+    public final int ecmaId;\r
+    public final int defaultKeySize;\r
+    public final int allowedKeySize[];\r
+    public final int blockSize;\r
+    public final int encryptedVerifierHashLength;\r
+    public final String xmlId;\r
+    public final boolean needsBouncyCastle;\r
+    \r
+    CipherAlgorithm(CipherProvider provider, String jceId, int ecmaId, int defaultKeySize, int allowedKeySize[], int blockSize, int encryptedVerifierHashLength, String xmlId, boolean needsBouncyCastle) {\r
+        this.provider = provider;\r
+        this.jceId = jceId;\r
+        this.ecmaId = ecmaId;\r
+        this.defaultKeySize = defaultKeySize;\r
+        this.allowedKeySize = allowedKeySize;\r
+        this.blockSize = blockSize;\r
+        this.encryptedVerifierHashLength = encryptedVerifierHashLength;\r
+        this.xmlId = xmlId;\r
+        this.needsBouncyCastle = needsBouncyCastle;\r
+    }\r
+\r
+    public static CipherAlgorithm fromEcmaId(int ecmaId) {\r
+        for (CipherAlgorithm ca : CipherAlgorithm.values()) {\r
+            if (ca.ecmaId == ecmaId) return ca;\r
+        }\r
+        throw new EncryptedDocumentException("cipher algorithm not found");\r
+    }\r
+    \r
+    public static CipherAlgorithm fromXmlId(String xmlId, int keySize) {\r
+        for (CipherAlgorithm ca : CipherAlgorithm.values()) {\r
+            if (!ca.xmlId.equals(xmlId)) continue;\r
+            for (int ks : ca.allowedKeySize) {\r
+                if (ks == keySize) return ca;\r
+            }\r
+        }\r
+        throw new EncryptedDocumentException("cipher algorithm not found");\r
+    }\r
+    \r
+\r
+}
\ No newline at end of file
diff --git a/src/java/org/apache/poi/poifs/crypt/CipherProvider.java b/src/java/org/apache/poi/poifs/crypt/CipherProvider.java
new file mode 100644 (file)
index 0000000..de343a9
--- /dev/null
@@ -0,0 +1,39 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+\r
+public enum CipherProvider {\r
+    rc4("RC4", 1),\r
+    aes("AES", 0x18);\r
+\r
+    public static CipherProvider fromEcmaId(int ecmaId) {\r
+        for (CipherProvider cp : CipherProvider.values()) {\r
+            if (cp.ecmaId == ecmaId) return cp;\r
+        }\r
+        throw new EncryptedDocumentException("cipher provider not found");\r
+    }    \r
+    \r
+    public final String jceId;\r
+    public final int ecmaId;\r
+    CipherProvider(String jceId, int ecmaId) {\r
+        this.jceId = jceId;\r
+        this.ecmaId = ecmaId;\r
+    }\r
+}
\ No newline at end of file
diff --git a/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java b/src/java/org/apache/poi/poifs/crypt/CryptoFunctions.java
new file mode 100644 (file)
index 0000000..75bf1e8
--- /dev/null
@@ -0,0 +1,258 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import java.nio.charset.Charset;\r
+import java.security.DigestException;\r
+import java.security.GeneralSecurityException;\r
+import java.security.MessageDigest;\r
+import java.security.Provider;\r
+import java.security.Security;\r
+import java.util.Arrays;\r
+\r
+import javax.crypto.Cipher;\r
+import javax.crypto.Mac;\r
+import javax.crypto.SecretKey;\r
+import javax.crypto.spec.IvParameterSpec;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.util.LittleEndian;\r
+import org.apache.poi.util.LittleEndianConsts;\r
+\r
+/**\r
+ * Helper functions used for standard and agile encryption\r
+ */\r
+public class CryptoFunctions {\r
+    /**\r
+     * 2.3.4.7 ECMA-376 Document Encryption Key Generation (Standard Encryption)\r
+     * 2.3.4.11 Encryption Key Generation (Agile Encryption)\r
+     * \r
+     * The encryption key for ECMA-376 document encryption [ECMA-376] using agile encryption MUST be \r
+     * generated by using the following method, which is derived from PKCS #5: Password-Based\r
+     * Cryptography Version 2.0 [RFC2898].\r
+     * \r
+     * Let H() be a hashing algorithm as determined by the PasswordKeyEncryptor.hashAlgorithm\r
+     * element, H_n be the hash data of the n-th iteration, and a plus sign (+) represent concatenation. The\r
+     * password MUST be provided as an array of Unicode characters. Limitations on the length of the\r
+     * password and the characters used by the password are implementation-dependent. The initial\r
+     * password hash is generated as follows:\r
+     * \r
+     * - H_0 = H(salt + password)\r
+     * \r
+     * The salt used MUST be generated randomly. The salt MUST be stored in the\r
+     * PasswordKeyEncryptor.saltValue element contained within the \EncryptionInfo stream (1) as\r
+     * specified in section 2.3.4.10. The hash is then iterated by using the following approach:\r
+     * \r
+     * - H_n = H(iterator + H_n-1)\r
+     * \r
+     * where iterator is an unsigned 32-bit value that is initially set to 0x00000000 and then incremented\r
+     * monotonically on each iteration until PasswordKey.spinCount iterations have been performed.\r
+     * The value of iterator on the last iteration MUST be one less than PasswordKey.spinCount.\r
+     * \r
+     * For POI, H_final will be calculated by {@link generateKey()}\r
+     *\r
+     * @param password\r
+     * @param hashAlgorithm\r
+     * @param salt\r
+     * @param spinCount\r
+     * @return\r
+     */\r
+    public static byte[] hashPassword(String password, HashAlgorithm hashAlgorithm, byte salt[], int spinCount) {\r
+        // If no password was given, use the default\r
+        if (password == null) {\r
+            password = Decryptor.DEFAULT_PASSWORD;\r
+        }\r
+        \r
+        MessageDigest hashAlg = getMessageDigest(hashAlgorithm);\r
+        \r
+        hashAlg.update(salt);\r
+        byte[] hash = hashAlg.digest(getUtf16LeString(password));\r
+        byte[] iterator = new byte[LittleEndianConsts.INT_SIZE];\r
+        \r
+        try {\r
+            for (int i = 0; i < spinCount; i++) {\r
+                LittleEndian.putInt(iterator, 0, i);\r
+                hashAlg.reset();\r
+                hashAlg.update(iterator);\r
+                hashAlg.update(hash);\r
+                hashAlg.digest(hash, 0, hash.length); // don't create hash buffer everytime new\r
+            }\r
+        } catch (DigestException e) {\r
+            throw new EncryptedDocumentException("error in password hashing");\r
+        }\r
+        \r
+        return hash;\r
+    }    \r
+\r
+    /**\r
+     * 2.3.4.12 Initialization Vector Generation (Agile Encryption)\r
+     * \r
+     * Initialization vectors are used in all cases for agile encryption. An initialization vector MUST be\r
+     * generated by using the following method, where H() is a hash function that MUST be the same as\r
+     * specified in section 2.3.4.11 and a plus sign (+) represents concatenation:\r
+     * 1. If a blockKey is provided, let IV be a hash of the KeySalt and the following value:\r
+     *    blockKey: IV = H(KeySalt + blockKey)\r
+     * 2. If a blockKey is not provided, let IV be equal to the following value:\r
+     *    KeySalt:IV = KeySalt.\r
+     * 3. If the number of bytes in the value of IV is less than the the value of the blockSize attribute\r
+     *    corresponding to the cipherAlgorithm attribute, pad the array of bytes by appending 0x36 until\r
+     *    the array is blockSize bytes. If the array of bytes is larger than blockSize bytes, truncate the\r
+     *    array to blockSize bytes. \r
+     **/\r
+    public static byte[] generateIv(HashAlgorithm hashAlgorithm, byte[] salt, byte[] blockKey, int blockSize) {\r
+        byte iv[] = salt;\r
+        if (blockKey != null) {\r
+            MessageDigest hashAlgo = getMessageDigest(hashAlgorithm);\r
+            hashAlgo.update(salt);\r
+            iv = hashAlgo.digest(blockKey);\r
+        }\r
+        return getBlock36(iv, blockSize);\r
+    }\r
+\r
+    /**\r
+     * 2.3.4.11 Encryption Key Generation (Agile Encryption)\r
+     * \r
+     * ... continued ...\r
+     * \r
+     * The final hash data that is used for an encryption key is then generated by using the following\r
+     * method:\r
+     * \r
+     * - H_final = H(H_n + blockKey)\r
+     * \r
+     * where blockKey represents an array of bytes used to prevent two different blocks from encrypting\r
+     * to the same cipher text.\r
+     * \r
+     * If the size of the resulting H_final is smaller than that of PasswordKeyEncryptor.keyBits, the key\r
+     * MUST be padded by appending bytes with a value of 0x36. If the hash value is larger in size than\r
+     * PasswordKeyEncryptor.keyBits, the key is obtained by truncating the hash value. \r
+     *\r
+     * @param passwordHash\r
+     * @param hashAlgorithm\r
+     * @param blockKey\r
+     * @param keySize\r
+     * @return\r
+     */\r
+    public static byte[] generateKey(byte[] passwordHash, HashAlgorithm hashAlgorithm, byte[] blockKey, int keySize) {\r
+        MessageDigest hashAlgo = getMessageDigest(hashAlgorithm);\r
+        hashAlgo.update(passwordHash);\r
+        byte[] key = hashAlgo.digest(blockKey);\r
+        return getBlock36(key, keySize);\r
+    }\r
+\r
+    public static Cipher getCipher(SecretKey key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode) {\r
+        return getCipher(key, cipherAlgorithm, chain, vec, cipherMode, null);\r
+    }\r
+\r
+    /**\r
+     * \r
+     *\r
+     * @param key\r
+     * @param chain\r
+     * @param vec\r
+     * @param cipherMode Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE\r
+     * @return\r
+     * @throws GeneralSecurityException\r
+     */\r
+    public static Cipher getCipher(SecretKey key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode, String padding) {\r
+        int keySizeInBytes = key.getEncoded().length;\r
+        if (padding == null) padding = "NoPadding";\r
+        \r
+        try {\r
+            // Ensure the JCE policies files allow for this sized key\r
+            if (Cipher.getMaxAllowedKeyLength(key.getAlgorithm()) < keySizeInBytes*8) {\r
+                throw new EncryptedDocumentException("Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files");\r
+            }\r
+\r
+            Cipher cipher;\r
+            if (cipherAlgorithm.needsBouncyCastle) {\r
+                registerBouncyCastle();\r
+                cipher = Cipher.getInstance(key.getAlgorithm() + "/" + chain.jceId + "/" + padding, "BC");\r
+            } else {\r
+                cipher = Cipher.getInstance(key.getAlgorithm() + "/" + chain.jceId + "/" + padding);\r
+            }\r
+            \r
+            if (vec == null) {\r
+                cipher.init(cipherMode, key);\r
+            } else {\r
+                IvParameterSpec iv = new IvParameterSpec(vec);\r
+                cipher.init(cipherMode, key, iv);\r
+            }\r
+            return cipher;\r
+        } catch (GeneralSecurityException e) {\r
+            throw new EncryptedDocumentException(e);\r
+        }\r
+    }    \r
+    \r
+    public static byte[] getBlock36(byte[] hash, int size) {\r
+        return getBlockX(hash, size, (byte)0x36);\r
+    }\r
+\r
+    public static byte[] getBlock0(byte[] hash, int size) {\r
+        return getBlockX(hash, size, (byte)0);\r
+    }\r
+    \r
+    private static byte[] getBlockX(byte[] hash, int size, byte fill) {\r
+        if (hash.length == size) return hash;\r
+        \r
+        byte[] result = new byte[size];\r
+        Arrays.fill(result, fill);\r
+        System.arraycopy(hash, 0, result, 0, Math.min(result.length, hash.length));\r
+        return result;\r
+    }\r
+    \r
+    public static byte[] getUtf16LeString(String str) {\r
+        Charset cs = Charset.forName("UTF-16LE");\r
+        return str.getBytes(cs);\r
+    }\r
+    \r
+    public static MessageDigest getMessageDigest(HashAlgorithm hashAlgorithm) {\r
+        try {\r
+            if (hashAlgorithm.needsBouncyCastle) {\r
+                registerBouncyCastle();\r
+                return MessageDigest.getInstance(hashAlgorithm.jceId, "BC");\r
+            } else {\r
+                return MessageDigest.getInstance(hashAlgorithm.jceId);\r
+            }\r
+        } catch (GeneralSecurityException e) {\r
+            throw new EncryptedDocumentException("hash algo not supported", e);\r
+        }\r
+    }\r
+    \r
+    public static Mac getMac(HashAlgorithm hashAlgorithm) {\r
+        try {\r
+            if (hashAlgorithm.needsBouncyCastle) {\r
+                registerBouncyCastle();\r
+                return Mac.getInstance(hashAlgorithm.jceHmacId, "BC");\r
+            } else {\r
+                return Mac.getInstance(hashAlgorithm.jceHmacId);\r
+            }\r
+        } catch (GeneralSecurityException e) {\r
+            throw new EncryptedDocumentException("hmac algo not supported", e);\r
+        }\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    private static void registerBouncyCastle() {\r
+        if (Security.getProvider("BC") != null) return;\r
+        try {\r
+            Class<Provider> clazz = (Class<Provider>)Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");\r
+            Security.addProvider(clazz.newInstance());\r
+        } catch (Exception e) {\r
+            throw new EncryptedDocumentException("Only the BouncyCastle provider supports your encryption settings - please add it to the classpath.");\r
+        }\r
+    }\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/DataSpaceMapUtils.java b/src/java/org/apache/poi/poifs/crypt/DataSpaceMapUtils.java
new file mode 100644 (file)
index 0000000..963151f
--- /dev/null
@@ -0,0 +1,365 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import java.io.IOException;\r
+import java.nio.charset.Charset;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.standard.EncryptionRecord;\r
+import org.apache.poi.poifs.filesystem.DirectoryEntry;\r
+import org.apache.poi.poifs.filesystem.DocumentEntry;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterEvent;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterListener;\r
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
+import org.apache.poi.util.LittleEndianConsts;\r
+import org.apache.poi.util.LittleEndianInput;\r
+import org.apache.poi.util.LittleEndianOutput;\r
+\r
+public class DataSpaceMapUtils {\r
+    public static void addDefaultDataSpace(DirectoryEntry dir) throws IOException {\r
+        DataSpaceMapEntry dsme = new DataSpaceMapEntry(\r
+                new int[]{ 0 }\r
+              , new String[]{ "EncryptedPackage" }\r
+              , "StrongEncryptionDataSpace"\r
+          );\r
+          DataSpaceMap dsm = new DataSpaceMap(new DataSpaceMapEntry[]{dsme});\r
+          createEncryptionEntry(dir, "\u0006DataSpaces/DataSpaceMap", dsm);\r
+\r
+          DataSpaceDefinition dsd = new DataSpaceDefinition(new String[]{ "StrongEncryptionTransform" });\r
+          createEncryptionEntry(dir, "\u0006DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace", dsd);\r
+\r
+          TransformInfoHeader tih = new TransformInfoHeader(\r
+                1\r
+              , "{FF9A3F03-56EF-4613-BDD5-5A41C1D07246}"\r
+              , "Microsoft.Container.EncryptionTransform"\r
+              , 1, 0, 1, 0, 1, 0\r
+          );\r
+          IRMDSTransformInfo irm = new IRMDSTransformInfo(tih, 0, null);\r
+          createEncryptionEntry(dir, "\u0006DataSpaces/TransformInfo/StrongEncryptionTransform/\u0006Primary", irm);\r
+          \r
+          DataSpaceVersionInfo dsvi = new DataSpaceVersionInfo("Microsoft.Container.DataSpaces", 1, 0, 1, 0, 1, 0);\r
+          createEncryptionEntry(dir, "\u0006DataSpaces/Version", dsvi);\r
+    }\r
+    \r
+    public static DocumentEntry createEncryptionEntry(DirectoryEntry dir, String path, EncryptionRecord out) throws IOException {\r
+        String parts[] = path.split("/");\r
+        for (int i=0; i<parts.length-1; i++) {\r
+            dir = dir.hasEntry(parts[i])\r
+                ? (DirectoryEntry)dir.getEntry(parts[i])\r
+                : dir.createDirectory(parts[i]);\r
+        }\r
+        \r
+        final byte buf[] = new byte[5000];        \r
+        LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0);\r
+        out.write(bos);\r
+        \r
+        return dir.createDocument(parts[parts.length-1], bos.getWriteIndex(), new POIFSWriterListener(){\r
+            public void processPOIFSWriterEvent(POIFSWriterEvent event) {\r
+                try {\r
+                    event.getStream().write(buf, 0, event.getLimit());\r
+                } catch (IOException e) {\r
+                    throw new EncryptedDocumentException(e);\r
+                }\r
+            }\r
+        });\r
+    }   \r
+    \r
+    public static class DataSpaceMap implements EncryptionRecord {\r
+        DataSpaceMapEntry entries[];\r
+        \r
+        public DataSpaceMap(DataSpaceMapEntry entries[]) {\r
+            this.entries = entries;\r
+        }\r
+        \r
+        public DataSpaceMap(LittleEndianInput is) {\r
+            @SuppressWarnings("unused")\r
+            int length = is.readInt();\r
+            int entryCount = is.readInt();\r
+            entries = new DataSpaceMapEntry[entryCount];\r
+            for (int i=0; i<entryCount; i++) {\r
+                entries[i] = new DataSpaceMapEntry(is);\r
+            }\r
+        }\r
+    \r
+        public void write(LittleEndianByteArrayOutputStream os) {\r
+            os.writeInt(8);\r
+            os.writeInt(entries.length);\r
+            for (DataSpaceMapEntry dsme : entries) {\r
+                dsme.write(os);\r
+            }\r
+        }\r
+    }\r
+    \r
+    public static class DataSpaceMapEntry implements EncryptionRecord {\r
+        int referenceComponentType[];\r
+        String referenceComponent[];\r
+        String dataSpaceName;\r
+        \r
+        public DataSpaceMapEntry(int referenceComponentType[], String referenceComponent[], String dataSpaceName) {\r
+            this.referenceComponentType = referenceComponentType;\r
+            this.referenceComponent = referenceComponent;\r
+            this.dataSpaceName = dataSpaceName;\r
+        }\r
+        \r
+        public DataSpaceMapEntry(LittleEndianInput is) {\r
+            @SuppressWarnings("unused")\r
+            int length = is.readInt();\r
+            int referenceComponentCount = is.readInt();\r
+            referenceComponentType = new int[referenceComponentCount];\r
+            referenceComponent = new String[referenceComponentCount];\r
+            for (int i=0; i<referenceComponentCount; i++) {\r
+                referenceComponentType[i] = is.readInt();\r
+                referenceComponent[i] = readUnicodeLPP4(is);\r
+            }\r
+            dataSpaceName = readUnicodeLPP4(is);\r
+        }\r
+        \r
+        public void write(LittleEndianByteArrayOutputStream os) {\r
+            int start = os.getWriteIndex();\r
+            LittleEndianOutput sizeOut = os.createDelayedOutput(LittleEndianConsts.INT_SIZE);\r
+            os.writeInt(referenceComponent.length);\r
+            for (int i=0; i<referenceComponent.length; i++) {\r
+                os.writeInt(referenceComponentType[i]);\r
+                writeUnicodeLPP4(os, referenceComponent[i]);\r
+            }\r
+            writeUnicodeLPP4(os, dataSpaceName);\r
+            sizeOut.writeInt(os.getWriteIndex()-start);\r
+        }\r
+    }\r
+    \r
+    public static class DataSpaceDefinition implements EncryptionRecord {\r
+        String transformer[];\r
+        \r
+        public DataSpaceDefinition(String transformer[]) {\r
+            this.transformer = transformer;\r
+        }\r
+        \r
+        public DataSpaceDefinition(LittleEndianInput is) {\r
+            @SuppressWarnings("unused")\r
+            int headerLength = is.readInt();\r
+            int transformReferenceCount = is.readInt();\r
+            transformer = new String[transformReferenceCount];\r
+            for (int i=0; i<transformReferenceCount; i++) {\r
+                transformer[i] = readUnicodeLPP4(is);\r
+            }\r
+        }\r
+        \r
+        public void write(LittleEndianByteArrayOutputStream bos) {\r
+            bos.writeInt(8);\r
+            bos.writeInt(transformer.length);\r
+            for (String str : transformer) {\r
+                writeUnicodeLPP4(bos, str);\r
+            }\r
+        }\r
+    }\r
+    \r
+    public static class IRMDSTransformInfo implements EncryptionRecord {\r
+        TransformInfoHeader transformInfoHeader;\r
+        int extensibilityHeader;\r
+        String xrMLLicense;\r
+        \r
+        public IRMDSTransformInfo(TransformInfoHeader transformInfoHeader, int extensibilityHeader, String xrMLLicense) {\r
+            this.transformInfoHeader = transformInfoHeader;\r
+            this.extensibilityHeader = extensibilityHeader;\r
+            this.xrMLLicense = xrMLLicense;\r
+        }\r
+        \r
+        public IRMDSTransformInfo(LittleEndianInput is) {\r
+            transformInfoHeader = new TransformInfoHeader(is);\r
+            extensibilityHeader = is.readInt();\r
+            xrMLLicense = readUtf8LPP4(is);\r
+            // finish with 0x04 (int) ???\r
+        }\r
+        \r
+        public void write(LittleEndianByteArrayOutputStream bos) {\r
+            transformInfoHeader.write(bos);\r
+            bos.writeInt(extensibilityHeader);\r
+            writeUtf8LPP4(bos, xrMLLicense);\r
+            bos.writeInt(4); // where does this 4 come from???\r
+        }\r
+    }\r
+    \r
+    public static class TransformInfoHeader implements EncryptionRecord {\r
+        int transformType;\r
+        String transformerId;\r
+        String transformerName;\r
+        int readerVersionMajor = 1, readerVersionMinor = 0;\r
+        int updaterVersionMajor = 1, updaterVersionMinor = 0;\r
+        int writerVersionMajor = 1, writerVersionMinor = 0;\r
+\r
+        public TransformInfoHeader(\r
+            int transformType,\r
+            String transformerId,\r
+            String transformerName,\r
+            int readerVersionMajor, int readerVersionMinor,\r
+            int updaterVersionMajor, int updaterVersionMinor,\r
+            int writerVersionMajor, int writerVersionMinor                \r
+        ){\r
+            this.transformType = transformType;\r
+            this.transformerId = transformerId;\r
+            this.transformerName = transformerName;\r
+            this.readerVersionMajor = readerVersionMajor;\r
+            this.readerVersionMinor = readerVersionMinor;\r
+            this.updaterVersionMajor = updaterVersionMajor;\r
+            this.updaterVersionMinor = updaterVersionMinor;\r
+            this.writerVersionMajor = writerVersionMajor;\r
+            this.writerVersionMinor = writerVersionMinor;\r
+        }\r
+        \r
+        public TransformInfoHeader(LittleEndianInput is) {\r
+            @SuppressWarnings("unused")\r
+            int length = is.readInt();\r
+            transformType = is.readInt();\r
+            transformerId = readUnicodeLPP4(is);\r
+            transformerName = readUnicodeLPP4(is);\r
+            readerVersionMajor = is.readShort();\r
+            readerVersionMinor = is.readShort();\r
+            updaterVersionMajor = is.readShort();\r
+            updaterVersionMinor = is.readShort();\r
+            writerVersionMajor = is.readShort();\r
+            writerVersionMinor = is.readShort();\r
+        }\r
+        \r
+        public void write(LittleEndianByteArrayOutputStream bos) {\r
+            int start = bos.getWriteIndex();\r
+            LittleEndianOutput sizeOut = bos.createDelayedOutput(LittleEndianConsts.INT_SIZE);\r
+            bos.writeInt(transformType);\r
+            writeUnicodeLPP4(bos, transformerId);\r
+            sizeOut.writeInt(bos.getWriteIndex()-start);\r
+            writeUnicodeLPP4(bos, transformerName);\r
+            bos.writeShort(readerVersionMajor);\r
+            bos.writeShort(readerVersionMinor); \r
+            bos.writeShort(updaterVersionMajor);\r
+            bos.writeShort(updaterVersionMinor);\r
+            bos.writeShort(writerVersionMajor); \r
+            bos.writeShort(writerVersionMinor); \r
+        }\r
+    }\r
+    \r
+    public static class DataSpaceVersionInfo implements EncryptionRecord {\r
+        String featureIdentifier;\r
+        int readerVersionMajor = 1, readerVersionMinor = 0;\r
+        int updaterVersionMajor = 1, updaterVersionMinor = 0;\r
+        int writerVersionMajor = 1, writerVersionMinor = 0;\r
+        \r
+        public DataSpaceVersionInfo(LittleEndianInput is) {\r
+            featureIdentifier = readUnicodeLPP4(is);\r
+            readerVersionMajor = is.readShort();\r
+            readerVersionMinor = is.readShort();\r
+            updaterVersionMajor = is.readShort();\r
+            updaterVersionMinor = is.readShort();\r
+            writerVersionMajor = is.readShort();\r
+            writerVersionMinor = is.readShort();\r
+        }\r
+        \r
+        public DataSpaceVersionInfo(\r
+            String featureIdentifier,\r
+            int readerVersionMajor, int readerVersionMinor,\r
+            int updaterVersionMajor, int updaterVersionMinor,\r
+            int writerVersionMajor, int writerVersionMinor                \r
+        ){\r
+            this.featureIdentifier = featureIdentifier;\r
+            this.readerVersionMajor = readerVersionMajor;\r
+            this.readerVersionMinor = readerVersionMinor;\r
+            this.updaterVersionMajor = updaterVersionMajor;\r
+            this.updaterVersionMinor = updaterVersionMinor;\r
+            this.writerVersionMajor = writerVersionMajor;\r
+            this.writerVersionMinor = writerVersionMinor;\r
+        }\r
+        \r
+        public void write(LittleEndianByteArrayOutputStream bos) {\r
+            writeUnicodeLPP4(bos, featureIdentifier);\r
+            bos.writeShort(readerVersionMajor);\r
+            bos.writeShort(readerVersionMinor); \r
+            bos.writeShort(updaterVersionMajor);\r
+            bos.writeShort(updaterVersionMinor);\r
+            bos.writeShort(writerVersionMajor); \r
+            bos.writeShort(writerVersionMinor); \r
+        }\r
+    }\r
+    \r
+    public static String readUnicodeLPP4(LittleEndianInput is) {\r
+        Charset cs = Charset.forName("UTF-16LE");\r
+        int length = is.readInt();\r
+        byte data[] = new byte[length];\r
+        is.readFully(data);\r
+        if (length%4==2) {\r
+            // Padding (variable): A set of bytes that MUST be of the correct size such that the size of the \r
+            // UNICODE-LP-P4 structure is a multiple of 4 bytes. If Padding is present, it MUST be exactly \r
+            // 2 bytes long, and each byte MUST be 0x00.            \r
+            is.readShort();\r
+        }\r
+        return new String(data, 0, data.length, cs);\r
+    }\r
+    \r
+    public static void writeUnicodeLPP4(LittleEndianOutput os, String str) {\r
+        Charset cs = Charset.forName("UTF-16LE");\r
+        byte buf[] = str.getBytes(cs);\r
+        os.writeInt(buf.length);\r
+        os.write(buf);\r
+        if (buf.length%4==2) {\r
+            os.writeShort(0);\r
+        }\r
+    }\r
+\r
+    public static String readUtf8LPP4(LittleEndianInput is) {\r
+        int length = is.readInt();\r
+        if (length == 0 || length == 4) {\r
+            @SuppressWarnings("unused")\r
+            int skip = is.readInt(); // ignore\r
+            return length == 0 ? null : "";\r
+        }\r
+        \r
+        byte data[] = new byte[length];\r
+        is.readFully(data);\r
+\r
+        // Padding (variable): A set of bytes that MUST be of correct size such that the size of the UTF-8-LP-P4\r
+        // structure is a multiple of 4 bytes. If Padding is present, each byte MUST be 0x00. If \r
+        // the length is exactly 0x00000000, this specifies a null string, and the entire structure uses \r
+        // exactly 4 bytes. If the length is exactly 0x00000004, this specifies an empty string, and the \r
+        // entire structure also uses exactly 4 bytes\r
+        int scratchedBytes = length%4;\r
+        if (scratchedBytes > 0) {\r
+            for (int i=0; i<(4-scratchedBytes); i++) {\r
+                is.readByte();\r
+            }\r
+        }\r
+        Charset cs = Charset.forName("UTF-8");\r
+        return new String(data, 0, data.length, cs);\r
+    }\r
+    \r
+    public static void writeUtf8LPP4(LittleEndianOutput os, String str) {\r
+        if (str == null || "".equals(str)) {\r
+            os.writeInt(str == null ? 0 : 4);\r
+            os.writeInt(0);\r
+        } else {\r
+            Charset cs = Charset.forName("UTF-8");\r
+            byte buf[] = str.getBytes(cs);\r
+            os.writeInt(buf.length);\r
+            os.write(buf);\r
+            int scratchBytes = buf.length%4;\r
+            if (scratchBytes > 0) {\r
+                for (int i=0; i<(4-scratchBytes); i++) {\r
+                    os.writeByte(0);\r
+                }\r
+            }\r
+        }        \r
+    }\r
+\r
+}\r
index 39876f2f4c0e925f8b4046503cd901c6b626fd8a..c2d0d5953b3679712f317ebded7a4b255b7f65a9 100644 (file)
@@ -18,21 +18,26 @@ package org.apache.poi.poifs.crypt;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.security.DigestException;
-import java.security.MessageDigest;
 import java.security.GeneralSecurityException;
-import java.security.NoSuchAlgorithmException;
+
+import javax.crypto.SecretKey;
+
+import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.util.LittleEndian;
-import org.apache.poi.util.LittleEndianConsts;
 
 public abstract class Decryptor {
     public static final String DEFAULT_PASSWORD="VelvetSweatshop";
+    
+    protected final EncryptionInfo info;
+    private SecretKey secretKey;
+    private byte[] verifier, integrityHmacKey, integrityHmacValue;
 
+    protected Decryptor(EncryptionInfo info) {
+        this.info = info;
+    }
+    
     /**
      * Return a stream with decrypted data.
      * <p>
@@ -68,15 +73,11 @@ public abstract class Decryptor {
     public abstract long getLength();
 
     public static Decryptor getInstance(EncryptionInfo info) {
-        int major = info.getVersionMajor();
-        int minor = info.getVersionMinor();
-
-        if (major == 4 && minor == 4)
-            return new AgileDecryptor(info);
-        else if (minor == 2 && (major == 3 || major == 4))
-            return new EcmaDecryptor(info);
-        else
+        Decryptor d = info.getDecryptor();
+        if (d == null) {
             throw new EncryptedDocumentException("Unsupported version");
+        }
+        return d;
     }
 
     public InputStream getDataStream(NPOIFSFileSystem fs) throws IOException, GeneralSecurityException {
@@ -86,40 +87,37 @@ public abstract class Decryptor {
     public InputStream getDataStream(POIFSFileSystem fs) throws IOException, GeneralSecurityException {
         return getDataStream(fs.getRoot());
     }
+    
+    // for tests
+    public byte[] getVerifier() {
+        return verifier;
+    }
 
-    protected byte[] hashPassword(EncryptionInfo info,
-                                  String password) throws NoSuchAlgorithmException {
-        // If no password was given, use the default
-        if (password == null) {
-            password = DEFAULT_PASSWORD;
-        }
-        
-        byte[] pass;
-        try {
-            pass = password.getBytes("UTF-16LE");
-        } catch (UnsupportedEncodingException e) {
-            throw new EncryptedDocumentException("UTF16 not supported");
-        }
+    public SecretKey getSecretKey() {
+        return secretKey;
+    }
+    
+    public byte[] getIntegrityHmacKey() {
+        return integrityHmacKey;
+    }
 
-        byte[] salt = info.getVerifier().getSalt();
-        
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-        sha1.update(salt);
-        byte[] hash = sha1.digest(pass);
-        byte[] iterator = new byte[LittleEndianConsts.INT_SIZE];
-        
-        try {
-        for (int i = 0; i < info.getVerifier().getSpinCount(); i++) {
-               LittleEndian.putInt(iterator, 0, i);
-            sha1.reset();
-            sha1.update(iterator);
-            sha1.update(hash);
-            sha1.digest(hash, 0, hash.length); // don't create hash buffer everytime new
-        }
-        } catch (DigestException e) {
-               throw new EncryptedDocumentException("error in password hashing");
-        }
-        
-        return hash;
+    public byte[] getIntegrityHmacValue() {
+        return integrityHmacValue;
+    }
+
+    protected void setSecretKey(SecretKey secretKey) {
+        this.secretKey = secretKey;
+    }
+
+    protected void setVerifier(byte[] verifier) {
+        this.verifier = verifier;
+    }
+
+    protected void setIntegrityHmacKey(byte[] integrityHmacKey) {
+        this.integrityHmacKey = integrityHmacKey;
+    }
+
+    protected void setIntegrityHmacValue(byte[] integrityHmacValue) {
+        this.integrityHmacValue = integrityHmacValue;
     }
 }
\ No newline at end of file
diff --git a/src/java/org/apache/poi/poifs/crypt/EcmaDecryptor.java b/src/java/org/apache/poi/poifs/crypt/EcmaDecryptor.java
deleted file mode 100644 (file)
index 65e9be9..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/* ====================================================================
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-==================================================================== */
-package org.apache.poi.poifs.crypt;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-
-import javax.crypto.Cipher;
-import javax.crypto.CipherInputStream;
-import javax.crypto.SecretKey;
-import javax.crypto.spec.SecretKeySpec;
-
-import org.apache.poi.poifs.filesystem.DirectoryNode;
-import org.apache.poi.poifs.filesystem.DocumentInputStream;
-import org.apache.poi.util.LittleEndian;
-
-/**
- */
-public class EcmaDecryptor extends Decryptor {
-    private final EncryptionInfo info;
-    private byte[] passwordHash;
-    private long _length = -1;
-
-    public EcmaDecryptor(EncryptionInfo info) {
-        this.info = info;
-    }
-
-    private byte[] generateKey(int block) throws NoSuchAlgorithmException {
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-
-        sha1.update(passwordHash);
-        byte[] blockValue = new byte[4];
-        LittleEndian.putInt(blockValue, 0, block);
-        byte[] finalHash = sha1.digest(blockValue);
-
-        int requiredKeyLength = info.getHeader().getKeySize()/8;
-
-        byte[] buff = new byte[64];
-
-        Arrays.fill(buff, (byte) 0x36);
-
-        for (int i=0; i<finalHash.length; i++) {
-            buff[i] = (byte) (buff[i] ^ finalHash[i]);
-        }
-
-        sha1.reset();
-        byte[] x1 = sha1.digest(buff);
-
-        Arrays.fill(buff, (byte) 0x5c);
-        for (int i=0; i<finalHash.length; i++) {
-            buff[i] = (byte) (buff[i] ^ finalHash[i]);
-        }
-
-        sha1.reset();
-        byte[] x2 = sha1.digest(buff);
-
-        byte[] x3 = new byte[x1.length + x2.length];
-        System.arraycopy(x1, 0, x3, 0, x1.length);
-        System.arraycopy(x2, 0, x3, x1.length, x2.length);
-
-        return truncateOrPad(x3, requiredKeyLength);
-    }
-
-    public boolean verifyPassword(String password) throws GeneralSecurityException {
-        passwordHash = hashPassword(info, password);
-
-        Cipher cipher = getCipher();
-
-        byte[] verifier = cipher.doFinal(info.getVerifier().getVerifier());
-
-        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
-        byte[] calcVerifierHash = sha1.digest(verifier);
-
-        byte[] verifierHash = truncateOrPad(cipher.doFinal(info.getVerifier().getVerifierHash()), calcVerifierHash.length);
-
-        return Arrays.equals(calcVerifierHash, verifierHash);
-    }
-
-    /**
-     * Returns a byte array of the requested length,
-     *  truncated or zero padded as needed.
-     * Behaves like Arrays.copyOf in Java 1.6
-     */
-    private byte[] truncateOrPad(byte[] source, int length) {
-       byte[] result = new byte[length];
-       System.arraycopy(source, 0, result, 0, Math.min(length, source.length));
-       if(length > source.length) {
-          for(int i=source.length; i<length; i++) {
-             result[i] = 0;
-          }
-       }
-       return result;
-    }
-
-    private Cipher getCipher() throws GeneralSecurityException {
-        byte[] key = generateKey(0);
-        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
-        SecretKey skey = new SecretKeySpec(key, "AES");
-        cipher.init(Cipher.DECRYPT_MODE, skey);
-
-        return cipher;
-    }
-
-    public InputStream getDataStream(DirectoryNode dir) throws IOException, GeneralSecurityException {
-        DocumentInputStream dis = dir.createDocumentInputStream("EncryptedPackage");
-
-        _length = dis.readLong();
-
-        return new CipherInputStream(dis, getCipher());
-    }
-
-    public long getLength(){
-        if(_length == -1) throw new IllegalStateException("EcmaDecryptor.getDataStream() was not called");
-        return _length;
-    }
-}
index e04c8623638d45d5bf15e1507708c239e33aee4b..adcf4c4275ad9f13d8d6016ac2d1dfa9d12eb8ad 100644 (file)
 ==================================================================== */
 package org.apache.poi.poifs.crypt;
 
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.poifs.filesystem.DocumentInputStream;
-import org.apache.poi.util.LittleEndianConsts;
-import org.w3c.dom.NamedNodeMap;
 
 /**
  * Reads and processes OOXML Encryption Headers
  * The constants are largely based on ZIP constants.
  */
-public class EncryptionHeader {
-    public static final int ALGORITHM_RC4 = 0x6801;
-    public static final int ALGORITHM_AES_128 = 0x660E;
-    public static final int ALGORITHM_AES_192 = 0x660F;
-    public static final int ALGORITHM_AES_256 = 0x6610;
-
-    public static final int HASH_NONE = 0x0000;
-    public static final int HASH_SHA1 = 0x8004;
-    public static final int HASH_SHA256 = 0x800C;
-    public static final int HASH_SHA384 = 0x800D;
-    public static final int HASH_SHA512 = 0x800E;
-
-    public static final int PROVIDER_RC4 = 1;
-    public static final int PROVIDER_AES = 0x18;
-
-    public static final int MODE_ECB = 1;
-    public static final int MODE_CBC = 2;
-    public static final int MODE_CFB = 3;
-
-    private final int flags;
-    private final int sizeExtra;
-    private final int algorithm;
-    private final int hashAlgorithm;
-    private final int keySize;
-    private final int blockSize;
-    private final int providerType;
-    private final int cipherMode;
-    private final byte[] keySalt;
-    private final String cspName;
-
-    public EncryptionHeader(DocumentInputStream is) throws IOException {
-        flags = is.readInt();
-        sizeExtra = is.readInt();
-        algorithm = is.readInt();
-        hashAlgorithm = is.readInt();
-        keySize = is.readInt();
-        blockSize = keySize;
-        providerType = is.readInt();
-
-        is.readLong(); // skip reserved
-
-        // CSPName may not always be specified
-        // In some cases, the sale value of the EncryptionVerifier has the details
-        is.mark(LittleEndianConsts.INT_SIZE+1);
-        int checkForSalt = is.readInt();
-        is.reset();
-        
-        if (checkForSalt == 16) {
-               cspName = "";
-        } else {
-            StringBuilder builder = new StringBuilder();
-            while (true) {
-                char c = (char) is.readShort();
-                if (c == 0) break;
-                builder.append(c);
-            }
-            cspName = builder.toString();
-        }
-        
-        cipherMode = MODE_ECB;
-        keySalt = null;
-    }
-
-    public EncryptionHeader(String descriptor) throws IOException {
-        NamedNodeMap keyData;
-        try {
-            ByteArrayInputStream is;
-            is = new ByteArrayInputStream(descriptor.getBytes());
-            keyData = DocumentBuilderFactory.newInstance()
-                .newDocumentBuilder().parse(is)
-                .getElementsByTagName("keyData").item(0).getAttributes();
-        } catch (Exception e) {
-            throw new EncryptedDocumentException("Unable to parse keyData");
-        }
-
-        keySize = Integer.parseInt(keyData.getNamedItem("keyBits")
-                                   .getNodeValue());
-        flags = 0;
-        sizeExtra = 0;
-        cspName = null;
-
-        blockSize = Integer.parseInt(keyData.getNamedItem("blockSize").
-                                         getNodeValue());
-        String cipher = keyData.getNamedItem("cipherAlgorithm").getNodeValue();
-
-        if ("AES".equals(cipher)) {
-            providerType = PROVIDER_AES;
-            switch (keySize) {
-              case 128: 
-                algorithm = ALGORITHM_AES_128; break;
-            case 192: 
-                algorithm = ALGORITHM_AES_192; break;
-            case 256: 
-                algorithm = ALGORITHM_AES_256; break;
-            default: 
-                throw new EncryptedDocumentException("Unsupported key length " + keySize);
-            }
-        } else {
-            throw new EncryptedDocumentException("Unsupported cipher " + cipher);
-        }
-
-        String chaining = keyData.getNamedItem("cipherChaining").getNodeValue();
-
-        if ("ChainingModeCBC".equals(chaining))
-            cipherMode = MODE_CBC;
-        else if ("ChainingModeCFB".equals(chaining))
-            cipherMode = MODE_CFB;
-        else
-            throw new EncryptedDocumentException("Unsupported chaining mode " + chaining);
-
-        String hashAlg = keyData.getNamedItem("hashAlgorithm").getNodeValue();
-        int hashSize = Integer.parseInt(
-                                    keyData.getNamedItem("hashSize").getNodeValue());
-
-        if ("SHA1".equals(hashAlg) && hashSize == 20) {
-            hashAlgorithm = HASH_SHA1;
-        }
-        else if ("SHA256".equals(hashAlg) && hashSize == 32) {
-            hashAlgorithm = HASH_SHA256;
-        }
-        else if ("SHA384".equals(hashAlg) && hashSize == 64) {
-            hashAlgorithm = HASH_SHA384;
-        }
-        else if ("SHA512".equals(hashAlg) && hashSize == 64) {
-            hashAlgorithm = HASH_SHA512;
-        }
-        else {
-            throw new EncryptedDocumentException("Unsupported hash algorithm: " + 
-                                                  hashAlg + " @ " + hashSize + " bytes");
-        }
-
-        String salt = keyData.getNamedItem("saltValue").getNodeValue();
-        int saltLength = Integer.parseInt(keyData.getNamedItem("saltSize")
-                                          .getNodeValue());
-        keySalt = Base64.decodeBase64(salt.getBytes());
-        if (keySalt.length != saltLength)
-            throw new EncryptedDocumentException("Invalid salt length");
-    }
+public abstract class EncryptionHeader {
+    public static final int ALGORITHM_RC4 = CipherAlgorithm.rc4.ecmaId;
+    public static final int ALGORITHM_AES_128 = CipherAlgorithm.aes128.ecmaId;
+    public static final int ALGORITHM_AES_192 = CipherAlgorithm.aes192.ecmaId;
+    public static final int ALGORITHM_AES_256 = CipherAlgorithm.aes256.ecmaId;
+    
+    public static final int HASH_NONE   = HashAlgorithm.none.ecmaId;
+    public static final int HASH_SHA1   = HashAlgorithm.sha1.ecmaId;
+    public static final int HASH_SHA256 = HashAlgorithm.sha256.ecmaId;
+    public static final int HASH_SHA384 = HashAlgorithm.sha384.ecmaId;
+    public static final int HASH_SHA512 = HashAlgorithm.sha512.ecmaId;
+
+    public static final int PROVIDER_RC4 = CipherProvider.rc4.ecmaId;
+    public static final int PROVIDER_AES = CipherProvider.aes.ecmaId;
+
+    public static final int MODE_ECB = ChainingMode.ecb.ecmaId;
+    public static final int MODE_CBC = ChainingMode.cbc.ecmaId;
+    public static final int MODE_CFB = ChainingMode.cfb.ecmaId;
+    
+    private int flags;
+    private int sizeExtra;
+    private CipherAlgorithm cipherAlgorithm;
+    private HashAlgorithm hashAlgorithm;
+    private int keyBits;
+    private int blockSize;
+    private CipherProvider providerType;
+    private ChainingMode chainingMode;
+    private byte[] keySalt;
+    private String cspName;
+    
+    protected EncryptionHeader() {}
 
+    /**
+     * @deprecated use getChainingMode().ecmaId
+     */
     public int getCipherMode() {
-        return cipherMode;
+        return chainingMode.ecmaId;
+    }
+    
+    public ChainingMode getChainingMode() {
+        return chainingMode;
+    }
+    
+    protected void setChainingMode(ChainingMode chainingMode) {
+        this.chainingMode = chainingMode;
     }
 
     public int getFlags() {
         return flags;
     }
+    
+    protected void setFlags(int flags) {
+        this.flags = flags;
+    }
 
     public int getSizeExtra() {
         return sizeExtra;
     }
+    
+    protected void setSizeExtra(int sizeExtra) {
+        this.sizeExtra = sizeExtra;
+    }
 
+    /**
+     * @deprecated use getCipherAlgorithm()
+     */
     public int getAlgorithm() {
-        return algorithm;
+        return cipherAlgorithm.ecmaId;
     }
 
+    public CipherAlgorithm getCipherAlgorithm() {
+        return cipherAlgorithm;
+    }
+    
+    protected void setCipherAlgorithm(CipherAlgorithm cipherAlgorithm) {
+        this.cipherAlgorithm = cipherAlgorithm;
+    }
+    
+    /**
+     * @deprecated use getHashAlgorithmEx()
+     */
     public int getHashAlgorithm() {
+        return hashAlgorithm.ecmaId;
+    }
+    
+    public HashAlgorithm getHashAlgorithmEx() {
         return hashAlgorithm;
     }
+    
+    protected void setHashAlgorithm(HashAlgorithm hashAlgorithm) {
+        this.hashAlgorithm = hashAlgorithm;
+    }
 
     public int getKeySize() {
-        return keySize;
+        return keyBits;
+    }
+    
+    protected void setKeySize(int keyBits) {
+        this.keyBits = keyBits;
     }
 
     public int getBlockSize() {
        return blockSize;
     }
     
+    protected void setBlockSize(int blockSize) {
+        this.blockSize = blockSize;
+    }
+    
     public byte[] getKeySalt() {
         return keySalt;
     }
+    
+    protected void setKeySalt(byte salt[]) {
+        this.keySalt = salt;
+    }
 
+    /**
+     * @deprecated use getCipherProvider()
+     */
     public int getProviderType() {
-        return providerType;
+        return providerType.ecmaId;
     }
 
+    public CipherProvider getCipherProvider() {
+        return providerType;
+    }    
+
+    protected void setCipherProvider(CipherProvider providerType) {
+        this.providerType = providerType;
+    }
+    
     public String getCspName() {
         return cspName;
     }
+    
+    protected void setCspName(String cspName) {
+        this.cspName = cspName;
+    }
 }
index b6dd0f0b29dba11335d39588fa28039b4d2965e2..f2c160811277f6b84c1b998537e0af94dfc57213 100644 (file)
 ==================================================================== */
 package org.apache.poi.poifs.crypt;
 
+import static org.apache.poi.poifs.crypt.EncryptionMode.agile;
+import static org.apache.poi.poifs.crypt.EncryptionMode.standard;
+
+import java.io.IOException;
+
+import org.apache.poi.EncryptedDocumentException;
 import org.apache.poi.poifs.filesystem.DirectoryNode;
 import org.apache.poi.poifs.filesystem.DocumentInputStream;
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 
-import java.io.IOException;
-
 /**
  */
 public class EncryptionInfo {
     private final int versionMajor;
     private final int versionMinor;
     private final int encryptionFlags;
-
+    
     private final EncryptionHeader header;
     private final EncryptionVerifier verifier;
+    private final Decryptor decryptor;
+    private final Encryptor encryptor;
 
     public EncryptionInfo(POIFSFileSystem fs) throws IOException {
        this(fs.getRoot());
     }
+    
     public EncryptionInfo(NPOIFSFileSystem fs) throws IOException {
        this(fs.getRoot());
     }
+    
     public EncryptionInfo(DirectoryNode dir) throws IOException {
         DocumentInputStream dis = dir.createDocumentInputStream("EncryptionInfo");
         versionMajor = dis.readShort();
         versionMinor = dis.readShort();
-
         encryptionFlags = dis.readInt();
-
-        if (versionMajor == 4 && versionMinor == 4 && encryptionFlags == 0x40) {
-            StringBuilder builder = new StringBuilder();
-            byte[] xmlDescriptor = new byte[dis.available()];
-            dis.read(xmlDescriptor);
-            for (byte b : xmlDescriptor)
-                builder.append((char)b);
-            String descriptor = builder.toString();
-            header = new EncryptionHeader(descriptor);
-            verifier = new EncryptionVerifier(descriptor);
+        
+        EncryptionMode encryptionMode;
+        if (versionMajor == agile.versionMajor
+            && versionMinor == agile.versionMinor
+            && encryptionFlags == agile.encryptionFlags) {
+            encryptionMode = agile;
         } else {
-            int hSize = dis.readInt();
-            header = new EncryptionHeader(dis);
-            if (header.getAlgorithm()==EncryptionHeader.ALGORITHM_RC4) {
-                verifier = new EncryptionVerifier(dis, 20);
-            } else {
-                verifier = new EncryptionVerifier(dis, 32);
-            }
+            encryptionMode = standard;
+        }
+        
+        EncryptionInfoBuilder eib;
+        try {
+            eib = getBuilder(encryptionMode);
+        } catch (ReflectiveOperationException e) {
+            throw new IOException(e);
         }
+
+        eib.initialize(this, dis);
+        header = eib.getHeader();
+        verifier = eib.getVerifier();
+        decryptor = eib.getDecryptor();
+        encryptor = eib.getEncryptor();
     }
 
+    public EncryptionInfo(POIFSFileSystem fs, EncryptionMode encryptionMode) throws IOException {
+        this(fs.getRoot(), encryptionMode);
+     }
+     
+     public EncryptionInfo(NPOIFSFileSystem fs, EncryptionMode encryptionMode) throws IOException {
+        this(fs.getRoot(), encryptionMode);
+     }
+     
+    public EncryptionInfo(
+          DirectoryNode dir
+        , EncryptionMode encryptionMode
+    ) throws EncryptedDocumentException {
+        this(dir, encryptionMode, null, null, -1, -1, null);
+    }
+    
+    public EncryptionInfo(
+        POIFSFileSystem fs
+      , EncryptionMode encryptionMode
+      , CipherAlgorithm cipherAlgorithm
+      , HashAlgorithm hashAlgorithm
+      , int keyBits
+      , int blockSize
+      , ChainingMode chainingMode
+    ) throws EncryptedDocumentException {
+        this(fs.getRoot(), encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
+    }
+    
+    public EncryptionInfo(
+        NPOIFSFileSystem fs
+      , EncryptionMode encryptionMode
+      , CipherAlgorithm cipherAlgorithm
+      , HashAlgorithm hashAlgorithm
+      , int keyBits
+      , int blockSize
+      , ChainingMode chainingMode
+    ) throws EncryptedDocumentException {
+        this(fs.getRoot(), encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
+    }
+        
+    public EncryptionInfo(
+          DirectoryNode dir
+        , EncryptionMode encryptionMode
+        , CipherAlgorithm cipherAlgorithm
+        , HashAlgorithm hashAlgorithm
+        , int keyBits
+        , int blockSize
+        , ChainingMode chainingMode
+    ) throws EncryptedDocumentException {
+        versionMajor = encryptionMode.versionMajor;
+        versionMinor = encryptionMode.versionMinor;
+        encryptionFlags = encryptionMode.encryptionFlags;
+
+        EncryptionInfoBuilder eib;
+        try {
+            eib = getBuilder(encryptionMode);
+        } catch (ReflectiveOperationException e) {
+            throw new EncryptedDocumentException(e);
+        }
+        
+        eib.initialize(this, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);
+        
+        header = eib.getHeader();
+        verifier = eib.getVerifier();
+        decryptor = eib.getDecryptor();
+        encryptor = eib.getEncryptor();
+    }
+
+    protected static EncryptionInfoBuilder getBuilder(EncryptionMode encryptionMode)
+    throws ReflectiveOperationException {
+        ClassLoader cl = Thread.currentThread().getContextClassLoader();
+        EncryptionInfoBuilder eib;
+        eib = (EncryptionInfoBuilder)cl.loadClass(encryptionMode.builder).newInstance();
+        return eib;
+    }
+    
     public int getVersionMajor() {
         return versionMajor;
     }
@@ -85,4 +170,12 @@ public class EncryptionInfo {
     public EncryptionVerifier getVerifier() {
         return verifier;
     }
+    
+    public Decryptor getDecryptor() {
+        return decryptor;
+    }
+
+    public Encryptor getEncryptor() {
+        return encryptor;
+    }
 }
diff --git a/src/java/org/apache/poi/poifs/crypt/EncryptionInfoBuilder.java b/src/java/org/apache/poi/poifs/crypt/EncryptionInfoBuilder.java
new file mode 100644 (file)
index 0000000..0c31fc8
--- /dev/null
@@ -0,0 +1,30 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.poifs.filesystem.DocumentInputStream;\r
+\r
+public interface EncryptionInfoBuilder {\r
+    void initialize(EncryptionInfo ei, DocumentInputStream dis) throws IOException;\r
+    void initialize(EncryptionInfo ei, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode);\r
+    EncryptionHeader getHeader();\r
+    EncryptionVerifier getVerifier();\r
+    Decryptor getDecryptor();\r
+    Encryptor getEncryptor();\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java b/src/java/org/apache/poi/poifs/crypt/EncryptionMode.java
new file mode 100644 (file)
index 0000000..4d91145
--- /dev/null
@@ -0,0 +1,35 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+public enum EncryptionMode {\r
+      standard("org.apache.poi.poifs.crypt.standard.StandardEncryptionInfoBuilder", 4, 2, 0x24)\r
+    , agile("org.apache.poi.poifs.crypt.agile.AgileEncryptionInfoBuilder", 4, 4, 0x40);\r
+    \r
+    public final String builder;\r
+    public final int versionMajor;\r
+    public final int versionMinor;\r
+    public final int encryptionFlags;\r
+    \r
+    EncryptionMode(String builder, int versionMajor, int versionMinor, int encryptionFlags) {\r
+        this.builder = builder;\r
+        this.versionMajor = versionMajor;\r
+        this.versionMinor = versionMinor;\r
+        this.encryptionFlags = encryptionFlags;\r
+    }\r
+}\r
index e29952bc9ae1c3e0584514359e3311efcb163076..ecb90e08e2022681472ef114197a4e70ae9f5235 100644 (file)
 ==================================================================== */
 package org.apache.poi.poifs.crypt;
 
-import java.io.ByteArrayInputStream;
-
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.poi.EncryptedDocumentException;
-import org.apache.poi.poifs.filesystem.DocumentInputStream;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * Used when checking if a key is valid for a document 
  */
-public class EncryptionVerifier {
-    private final byte[] salt;
-    private final byte[] verifier;
-    private final byte[] verifierHash;
-    private final byte[] encryptedKey;
-    private final int verifierHashSize;
-    private final int spinCount;
-    private final int algorithm;
-    private final int cipherMode;
-
-    public EncryptionVerifier(String descriptor) {
-        NamedNodeMap keyData = null;
-        try {
-            ByteArrayInputStream is;
-            is = new ByteArrayInputStream(descriptor.getBytes());
-            NodeList keyEncryptor = DocumentBuilderFactory.newInstance()
-                .newDocumentBuilder().parse(is)
-                .getElementsByTagName("keyEncryptor").item(0).getChildNodes();
-            for (int i = 0; i < keyEncryptor.getLength(); i++) {
-                Node node = keyEncryptor.item(i);
-                if (node.getNodeName().equals("p:encryptedKey")) {
-                    keyData = node.getAttributes();
-                    break;
-                }
-            }
-            if (keyData == null)
-                throw new EncryptedDocumentException("");
-        } catch (Exception e) {
-            throw new EncryptedDocumentException("Unable to parse keyEncryptor");
-        }
-
-        spinCount = Integer.parseInt(keyData.getNamedItem("spinCount")
-                                     .getNodeValue());
-        verifier = Base64.decodeBase64(keyData
-                                       .getNamedItem("encryptedVerifierHashInput")
-                                       .getNodeValue().getBytes());
-        salt = Base64.decodeBase64(keyData.getNamedItem("saltValue")
-                                   .getNodeValue().getBytes());
-
-        encryptedKey = Base64.decodeBase64(keyData
-                                           .getNamedItem("encryptedKeyValue")
-                                           .getNodeValue().getBytes());
-
-        int saltSize = Integer.parseInt(keyData.getNamedItem("saltSize")
-                                        .getNodeValue());
-        if (saltSize != salt.length)
-            throw new EncryptedDocumentException("Invalid salt size");
-
-        verifierHash = Base64.decodeBase64(keyData
-                                           .getNamedItem("encryptedVerifierHashValue")
-                                           .getNodeValue().getBytes());
-
-        int blockSize = Integer.parseInt(keyData.getNamedItem("blockSize")
-                                         .getNodeValue());
-
-        String alg = keyData.getNamedItem("cipherAlgorithm").getNodeValue();
-        
-        int keyBits = Integer.parseInt(keyData.getNamedItem("keyBits")
-                .getNodeValue());
-
-        if ("AES".equals(alg)) {
-               switch (keyBits) {
-              case 128: 
-                  algorithm = EncryptionHeader.ALGORITHM_AES_128; break;
-              case 192: 
-                  algorithm = EncryptionHeader.ALGORITHM_AES_192; break;
-              case 256: 
-                  algorithm = EncryptionHeader.ALGORITHM_AES_256; break;
-              default: 
-                  throw new EncryptedDocumentException("Unsupported key size");
-               }
-        } else {
-            throw new EncryptedDocumentException("Unsupported cipher");
-        }
-
-        String chain = keyData.getNamedItem("cipherChaining").getNodeValue();
-        if ("ChainingModeCBC".equals(chain))
-            cipherMode = EncryptionHeader.MODE_CBC;
-        else if ("ChainingModeCFB".equals(chain))
-            cipherMode = EncryptionHeader.MODE_CFB;
-        else
-            throw new EncryptedDocumentException("Unsupported chaining mode");
-
-        verifierHashSize = Integer.parseInt(keyData.getNamedItem("hashSize")
-                                            .getNodeValue());
-    }
-
-    public EncryptionVerifier(DocumentInputStream is, int encryptedLength) {
-        int saltSize = is.readInt();
-
-        if (saltSize!=16) {
-            throw new RuntimeException("Salt size != 16 !?");
-        }
-
-        salt = new byte[16];
-        is.readFully(salt);
-        verifier = new byte[16];
-        is.readFully(verifier);
-
-        verifierHashSize = is.readInt();
-
-        verifierHash = new byte[encryptedLength];
-        is.readFully(verifierHash);
-
-        spinCount = 50000;
-        algorithm = EncryptionHeader.ALGORITHM_AES_128;
-        cipherMode = EncryptionHeader.MODE_ECB;
-        encryptedKey = null;
-    }
+public abstract class EncryptionVerifier {
+    private byte[] salt;
+    private byte[] encryptedVerifier;
+    private byte[] encryptedVerifierHash;
+    private byte[] encryptedKey;
+    // protected int verifierHashSize;
+    private int spinCount;
+    private CipherAlgorithm cipherAlgorithm;
+    private ChainingMode chainingMode;
+    private HashAlgorithm hashAlgorithm;
+    
+    protected EncryptionVerifier() {}
 
     public byte[] getSalt() {
         return salt;
     }
 
+    /**
+     * The method name is misleading - you'll get the encrypted verifier, not the plain verifier
+     * @deprecated use getEncryptedVerifier()
+     */
     public byte[] getVerifier() {
-        return verifier;
+        return encryptedVerifier;
     }
 
+    public byte[] getEncryptedVerifier() {
+        return encryptedVerifier;
+    }    
+    
+    /**
+     * The method name is misleading - you'll get the encrypted verifier hash, not the plain verifier hash
+     * @deprecated use getEnryptedVerifierHash
+     */
     public byte[] getVerifierHash() {
-        return verifierHash;
+        return encryptedVerifierHash;
     }
 
+    public byte[] getEncryptedVerifierHash() {
+        return encryptedVerifierHash;
+    }    
+    
     public int getSpinCount() {
         return spinCount;
     }
 
     public int getCipherMode() {
-        return cipherMode;
+        return chainingMode.ecmaId;
     }
 
     public int getAlgorithm() {
-        return algorithm;
+        return cipherAlgorithm.ecmaId;
+    }
+
+    /**
+     * @deprecated use getCipherAlgorithm().jceId
+     */
+    public String getAlgorithmName() {
+        return cipherAlgorithm.jceId;
     }
 
     public byte[] getEncryptedKey() {
         return encryptedKey;
     }
+    
+    public CipherAlgorithm getCipherAlgorithm() {
+        return cipherAlgorithm;
+    }
+    
+    public HashAlgorithm getHashAlgorithm() {
+        return hashAlgorithm;
+    }
+    
+    public ChainingMode getChainingMode() {
+        return chainingMode;
+    }
+
+    protected void setSalt(byte[] salt) {
+        this.salt = salt;
+    }
+
+    protected void setEncryptedVerifier(byte[] encryptedVerifier) {
+        this.encryptedVerifier = encryptedVerifier;
+    }
+
+    protected void setEncryptedVerifierHash(byte[] encryptedVerifierHash) {
+        this.encryptedVerifierHash = encryptedVerifierHash;
+    }
+
+    protected void setEncryptedKey(byte[] encryptedKey) {
+        this.encryptedKey = encryptedKey;
+    }
+
+    protected void setSpinCount(int spinCount) {
+        this.spinCount = spinCount;
+    }
+
+    protected void setCipherAlgorithm(CipherAlgorithm cipherAlgorithm) {
+        this.cipherAlgorithm = cipherAlgorithm;
+    }
+
+    protected void setChainingMode(ChainingMode chainingMode) {
+        this.chainingMode = chainingMode;
+    }
+
+    protected void setHashAlgorithm(HashAlgorithm hashAlgorithm) {
+        this.hashAlgorithm = hashAlgorithm;
+    }
+    
+    
 }
diff --git a/src/java/org/apache/poi/poifs/crypt/Encryptor.java b/src/java/org/apache/poi/poifs/crypt/Encryptor.java
new file mode 100644 (file)
index 0000000..abfd693
--- /dev/null
@@ -0,0 +1,65 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+import java.security.GeneralSecurityException;\r
+\r
+import javax.crypto.SecretKey;\r
+\r
+import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+\r
+public abstract class Encryptor {\r
+    private SecretKey secretKey;\r
+    \r
+    /**\r
+     * Return a output stream for encrypted data.\r
+     *\r
+     * @param dir the node to write to\r
+     * @return encrypted stream\r
+     */\r
+    public abstract OutputStream getDataStream(DirectoryNode dir)\r
+        throws IOException, GeneralSecurityException;\r
+\r
+    // for tests\r
+    public abstract void confirmPassword(String password, byte keySpec[], byte keySalt[], byte verifier[], byte verifierSalt[], byte integritySalt[]);\r
+    \r
+    public abstract void confirmPassword(String password);\r
+       \r
+       public static Encryptor getInstance(EncryptionInfo info) {\r
+           return info.getEncryptor();\r
+    }\r
+\r
+    public OutputStream getDataStream(NPOIFSFileSystem fs) throws IOException, GeneralSecurityException {\r
+        return getDataStream(fs.getRoot());\r
+    }\r
+\r
+    public OutputStream getDataStream(POIFSFileSystem fs) throws IOException, GeneralSecurityException {\r
+        return getDataStream(fs.getRoot());\r
+    }\r
+\r
+    public SecretKey getSecretKey() {\r
+        return secretKey;\r
+    }\r
+\r
+    protected void setSecretKey(SecretKey secretKey) {\r
+        this.secretKey = secretKey;\r
+    }\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/HashAlgorithm.java b/src/java/org/apache/poi/poifs/crypt/HashAlgorithm.java
new file mode 100644 (file)
index 0000000..cd62883
--- /dev/null
@@ -0,0 +1,66 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+\r
+public enum HashAlgorithm {\r
+    none     (         "", 0x0000,           "",  0,               "", false),\r
+    sha1     (    "SHA-1", 0x8004,       "SHA1", 20,       "HmacSHA1", false),\r
+    sha256   (  "SHA-256", 0x800C,     "SHA256", 32,     "HmacSHA256", false),\r
+    sha384   (  "SHA-384", 0x800D,     "SHA384", 48,     "HmacSHA384", false),\r
+    sha512   (  "SHA-512", 0x800E,     "SHA512", 64,     "HmacSHA512", false),\r
+    /* only for agile encryption */\r
+    md5      (      "MD5",     -1,        "MD5", 16,        "HmacMD5", false),\r
+    // although sunjc2 supports md2, hmac-md2 is only supported by bouncycastle\r
+    md2      (      "MD2",     -1,        "MD2", 16,       "Hmac-MD2", true),\r
+    ripemd128("RipeMD128",     -1, "RIPEMD-128", 16, "HMac-RipeMD128", true),\r
+    ripemd160("RipeMD160",     -1, "RIPEMD-160", 20, "HMac-RipeMD160", true),\r
+    whirlpool("Whirlpool",     -1,  "WHIRLPOOL", 64, "HMac-Whirlpool", true),\r
+    ;\r
+\r
+    public final String jceId;\r
+    public final int ecmaId;\r
+    public final String ecmaString;\r
+    public final int hashSize;\r
+    public final String jceHmacId;\r
+    public final boolean needsBouncyCastle;\r
+    \r
+    HashAlgorithm(String jceId, int ecmaId, String ecmaString, int hashSize, String jceHmacId, boolean needsBouncyCastle) {\r
+        this.jceId = jceId;\r
+        this.ecmaId = ecmaId;\r
+        this.ecmaString = ecmaString;\r
+        this.hashSize = hashSize;\r
+        this.jceHmacId = jceHmacId;\r
+        this.needsBouncyCastle = needsBouncyCastle;\r
+    }\r
+    \r
+    public static HashAlgorithm fromEcmaId(int ecmaId) {\r
+        for (HashAlgorithm ha : values()) {\r
+            if (ha.ecmaId == ecmaId) return ha;\r
+        }\r
+        throw new EncryptedDocumentException("hash algorithm not found");\r
+    }    \r
+    \r
+    public static HashAlgorithm fromEcmaId(String ecmaString) {\r
+        for (HashAlgorithm ha : values()) {\r
+            if (ha.ecmaString.equals(ecmaString)) return ha;\r
+        }\r
+        throw new EncryptedDocumentException("hash algorithm not found");\r
+    }\r
+}
\ No newline at end of file
diff --git a/src/java/org/apache/poi/poifs/crypt/package.html b/src/java/org/apache/poi/poifs/crypt/package.html
new file mode 100644 (file)
index 0000000..969d5e1
--- /dev/null
@@ -0,0 +1,44 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<html>\r
+<head>\r
+</head>\r
+<body bgcolor="white">\r
+\r
+<p>Implementation of the <a href="http://msdn.microsoft.com/en-us/library/dd952186(v=office.12).aspx">ECMA-376 Document Encryption</a></p>\r
+<p>The implementation is split into three packages:</p>\r
+<ul>\r
+<li>This package contains common functions for both current implemented cipher modes.</li>\r
+<li>the {@link org.apache.poi.poifs.crypt.standard standard} package is part of the base poi jar and contains classes for the standard encryption ...</li>\r
+<li>the {@link org.apache.poi.poifs.crypt.agile agile} package is part of the poi ooxml jar and the provides agile encryption support.</li>\r
+</ul>\r
+\r
+<h2>Related Documentation</h2>\r
+\r
+Some implementations informations can be found under:\r
+<ul>\r
+<li><a href="http://poi.apache.org/encryption.html">Apache POI - Encryption support</a>\r
+</ul>\r
+\r
+<!-- Put @see and @since tags down here. -->\r
+@see org.apache.poi.poifs.crypt.standard\r
+@see org.apache.poi.poifs.crypt.agile\r
+</body>\r
+</html>\r
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/EncryptionRecord.java b/src/java/org/apache/poi/poifs/crypt/standard/EncryptionRecord.java
new file mode 100644 (file)
index 0000000..bf65fbe
--- /dev/null
@@ -0,0 +1,23 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.standard;\r
+\r
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
+\r
+public interface EncryptionRecord {\r
+    void write(LittleEndianByteArrayOutputStream os);\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardDecryptor.java
new file mode 100644 (file)
index 0000000..18729a1
--- /dev/null
@@ -0,0 +1,158 @@
+/* ====================================================================
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================== */
+package org.apache.poi.poifs.crypt.standard;
+
+import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+
+import javax.crypto.Cipher;
+import javax.crypto.CipherInputStream;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.poifs.crypt.ChainingMode;
+import org.apache.poi.poifs.crypt.CryptoFunctions;
+import org.apache.poi.poifs.crypt.Decryptor;
+import org.apache.poi.poifs.crypt.EncryptionHeader;
+import org.apache.poi.poifs.crypt.EncryptionInfo;
+import org.apache.poi.poifs.crypt.EncryptionVerifier;
+import org.apache.poi.poifs.crypt.HashAlgorithm;
+import org.apache.poi.poifs.filesystem.DirectoryNode;
+import org.apache.poi.poifs.filesystem.DocumentInputStream;
+import org.apache.poi.util.BoundedInputStream;
+import org.apache.poi.util.LittleEndian;
+
+/**
+ */
+public class StandardDecryptor extends Decryptor {
+    private long _length = -1;
+
+    protected StandardDecryptor(EncryptionInfo info) {
+        super(info);
+    }
+
+    public boolean verifyPassword(String password) {
+        EncryptionVerifier ver = info.getVerifier();
+        SecretKey skey = generateSecretKey(password, ver, getKeySizeInBytes());
+        Cipher cipher = getCipher(skey);
+
+        try {
+            byte encryptedVerifier[] = ver.getEncryptedVerifier();
+            byte verifier[] = cipher.doFinal(encryptedVerifier);
+            setVerifier(verifier);
+            MessageDigest sha1 = MessageDigest.getInstance(ver.getHashAlgorithm().jceId);
+            byte[] calcVerifierHash = sha1.digest(verifier);
+            byte encryptedVerifierHash[] = ver.getEncryptedVerifierHash();
+            byte decryptedVerifierHash[] = cipher.doFinal(encryptedVerifierHash);
+            byte[] verifierHash = truncateOrPad(decryptedVerifierHash, calcVerifierHash.length);
+    
+            if (Arrays.equals(calcVerifierHash, verifierHash)) {
+                setSecretKey(skey);
+                return true;
+            } else {
+                return false;
+            }
+        } catch (GeneralSecurityException e) {
+            throw new EncryptedDocumentException(e);
+        }
+    }
+    
+    protected static SecretKey generateSecretKey(String password, EncryptionVerifier ver, int keySize) {
+        HashAlgorithm hashAlgo = ver.getHashAlgorithm();
+
+        byte pwHash[] = hashPassword(password, hashAlgo, ver.getSalt(), ver.getSpinCount());
+
+        byte[] blockKey = new byte[4];
+        LittleEndian.putInt(blockKey, 0, 0);
+
+        byte[] finalHash = CryptoFunctions.generateKey(pwHash, hashAlgo, blockKey, hashAlgo.hashSize);
+        byte x1[] = fillAndXor(finalHash, (byte) 0x36);
+        byte x2[] = fillAndXor(finalHash, (byte) 0x5c);
+
+        byte[] x3 = new byte[x1.length + x2.length];
+        System.arraycopy(x1, 0, x3, 0, x1.length);
+        System.arraycopy(x2, 0, x3, x1.length, x2.length);
+        
+        byte[] key = truncateOrPad(x3, keySize);
+
+        SecretKey skey = new SecretKeySpec(key, ver.getCipherAlgorithm().jceId);
+        return skey;
+    }
+
+    protected static byte[] fillAndXor(byte hash[], byte fillByte) {
+        byte[] buff = new byte[64];
+        Arrays.fill(buff, fillByte);
+
+        for (int i=0; i<hash.length; i++) {
+            buff[i] = (byte) (buff[i] ^ hash[i]);
+        }
+
+        try {
+            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
+            return sha1.digest(buff);
+        } catch (NoSuchAlgorithmException e) {
+            throw new EncryptedDocumentException("hash algo not supported", e);
+        }
+    }
+
+    /**
+     * Returns a byte array of the requested length,
+     *  truncated or zero padded as needed.
+     * Behaves like Arrays.copyOf in Java 1.6
+     */
+    protected static byte[] truncateOrPad(byte[] source, int length) {
+       byte[] result = new byte[length];
+       System.arraycopy(source, 0, result, 0, Math.min(length, source.length));
+       if(length > source.length) {
+          for(int i=source.length; i<length; i++) {
+             result[i] = 0;
+          }
+       }
+       return result;
+    }
+
+    private Cipher getCipher(SecretKey key) {
+        EncryptionHeader em = info.getHeader();
+        ChainingMode cm = em.getChainingMode();
+        assert(cm == ChainingMode.ecb);
+        return CryptoFunctions.getCipher(key, em.getCipherAlgorithm(), cm, null, Cipher.DECRYPT_MODE);
+    }
+
+    public InputStream getDataStream(DirectoryNode dir) throws IOException {
+        DocumentInputStream dis = dir.createDocumentInputStream("EncryptedPackage");
+
+        _length = dis.readLong();
+
+        return new BoundedInputStream(new CipherInputStream(dis, getCipher(getSecretKey())), _length);
+    }
+
+    public long getLength(){
+        if(_length == -1) throw new IllegalStateException("Decryptor.getDataStream() was not called");
+        return _length;
+    }
+
+    protected int getKeySizeInBytes() {
+        return info.getHeader().getKeySize()/8;
+    }
+}
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionHeader.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionHeader.java
new file mode 100644 (file)
index 0000000..213cc0b
--- /dev/null
@@ -0,0 +1,116 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.standard;\r
+\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getUtf16LeString;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.poifs.crypt.ChainingMode;\r
+import org.apache.poi.poifs.crypt.CipherAlgorithm;\r
+import org.apache.poi.poifs.crypt.CipherProvider;\r
+import org.apache.poi.poifs.crypt.EncryptionHeader;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
+import org.apache.poi.poifs.filesystem.DocumentInputStream;\r
+import org.apache.poi.util.BitField;\r
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
+import org.apache.poi.util.LittleEndianConsts;\r
+import org.apache.poi.util.LittleEndianOutput;\r
+\r
+public class StandardEncryptionHeader extends EncryptionHeader implements EncryptionRecord {\r
+    // A flag that specifies whether CryptoAPI RC4 or ECMA-376 encryption \r
+    // [ECMA-376] is used. It MUST be 1 unless fExternal is 1. If fExternal is 1, it MUST be 0.\r
+    private static BitField flagsCryptoAPI = new BitField(0x04);\r
+\r
+    // A value that MUST be 0 if document properties are encrypted. The \r
+    // encryption of document properties is specified in section 2.3.5.4 [MS-OFFCRYPTO].\r
+    @SuppressWarnings("unused")\r
+    private static BitField flagsDocProps = new BitField(0x08);\r
+    \r
+    // A value that MUST be 1 if extensible encryption is used,. If this value is 1, \r
+    // the value of every other field in this structure MUST be 0.\r
+    @SuppressWarnings("unused")\r
+    private static BitField flagsExternal = new BitField(0x10);\r
+    \r
+    // A value that MUST be 1 if the protected content is an ECMA-376 document \r
+    // [ECMA-376]. If the fAES bit is 1, the fCryptoAPI bit MUST also be 1.\r
+    private static BitField flagsAES = new BitField(0x20);\r
+    \r
+    protected StandardEncryptionHeader(DocumentInputStream is) throws IOException {\r
+        setFlags(is.readInt());\r
+        setSizeExtra(is.readInt());\r
+        setCipherAlgorithm(CipherAlgorithm.fromEcmaId(is.readInt()));\r
+        setHashAlgorithm(HashAlgorithm.fromEcmaId(is.readInt()));\r
+        setKeySize(is.readInt());\r
+        setBlockSize(getKeySize());\r
+        setCipherProvider(CipherProvider.fromEcmaId(is.readInt()));\r
+\r
+        is.readLong(); // skip reserved\r
+\r
+        // CSPName may not always be specified\r
+        // In some cases, the salt value of the EncryptionVerifier is the next chunk of data\r
+        is.mark(LittleEndianConsts.INT_SIZE+1);\r
+        int checkForSalt = is.readInt();\r
+        is.reset();\r
+        \r
+        if (checkForSalt == 16) {\r
+            setCspName("");\r
+        } else {\r
+            StringBuilder builder = new StringBuilder();\r
+            while (true) {\r
+                char c = (char) is.readShort();\r
+                if (c == 0) break;\r
+                builder.append(c);\r
+            }\r
+            setCspName(builder.toString());\r
+        }\r
+        \r
+        setChainingMode(ChainingMode.ecb);\r
+        setKeySalt(null);\r
+    }\r
+\r
+    protected StandardEncryptionHeader(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {\r
+        setCipherAlgorithm(cipherAlgorithm);\r
+        setHashAlgorithm(hashAlgorithm);\r
+        setKeySize(keyBits);\r
+        setBlockSize(blockSize);\r
+        setCipherProvider(cipherAlgorithm.provider);\r
+        setFlags(flagsCryptoAPI.setBoolean(0, true)\r
+                | flagsAES.setBoolean(0, cipherAlgorithm.provider == CipherProvider.aes));\r
+        // see http://msdn.microsoft.com/en-us/library/windows/desktop/bb931357(v=vs.85).aspx for a full list\r
+        // setCspName("Microsoft Enhanced RSA and AES Cryptographic Provider");\r
+    }\r
+    \r
+    public void write(LittleEndianByteArrayOutputStream bos) {\r
+        int startIdx = bos.getWriteIndex();\r
+        LittleEndianOutput sizeOutput = bos.createDelayedOutput(LittleEndianConsts.INT_SIZE);\r
+        bos.writeInt(getFlags());\r
+        bos.writeInt(0); // size extra\r
+        bos.writeInt(getCipherAlgorithm().ecmaId);\r
+        bos.writeInt(getHashAlgorithmEx().ecmaId);\r
+        bos.writeInt(getKeySize());\r
+        bos.writeInt(getCipherProvider().ecmaId);\r
+        bos.writeInt(0); // reserved1\r
+        bos.writeInt(0); // reserved2\r
+        if (getCspName() != null) {\r
+            bos.write(getUtf16LeString(getCspName()));\r
+            bos.writeShort(0);\r
+        }\r
+        int headerSize = bos.getWriteIndex()-startIdx-LittleEndianConsts.INT_SIZE;\r
+        sizeOutput.writeInt(headerSize);        \r
+    }\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionInfoBuilder.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionInfoBuilder.java
new file mode 100644 (file)
index 0000000..0480ec4
--- /dev/null
@@ -0,0 +1,106 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.standard;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.ChainingMode;\r
+import org.apache.poi.poifs.crypt.CipherAlgorithm;\r
+import org.apache.poi.poifs.crypt.EncryptionInfo;\r
+import org.apache.poi.poifs.crypt.EncryptionInfoBuilder;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
+import org.apache.poi.poifs.filesystem.DocumentInputStream;\r
+\r
+public class StandardEncryptionInfoBuilder implements EncryptionInfoBuilder {\r
+    \r
+    EncryptionInfo info;\r
+    StandardEncryptionHeader header;\r
+    StandardEncryptionVerifier verifier;\r
+    StandardDecryptor decryptor;\r
+    StandardEncryptor encryptor;\r
+\r
+    public void initialize(EncryptionInfo info, DocumentInputStream dis) throws IOException {\r
+        this.info = info;\r
+        \r
+        @SuppressWarnings("unused")\r
+        int hSize = dis.readInt();\r
+        header = new StandardEncryptionHeader(dis);\r
+        verifier = new StandardEncryptionVerifier(dis, header);\r
+\r
+        if (info.getVersionMinor() == 2 && (info.getVersionMajor() == 3 || info.getVersionMajor() == 4)) {\r
+            decryptor = new StandardDecryptor(info);\r
+        }\r
+    }\r
+    \r
+    public void initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {\r
+        this.info = info;\r
+\r
+        if (cipherAlgorithm == null) {\r
+            cipherAlgorithm = CipherAlgorithm.rc4;\r
+        }\r
+        if (hashAlgorithm == null) {\r
+            hashAlgorithm = HashAlgorithm.sha1;\r
+        }\r
+        if (hashAlgorithm != HashAlgorithm.sha1) {\r
+            throw new EncryptedDocumentException("Standard encryption only supports SHA-1.");\r
+        }\r
+        if (chainingMode == null) {\r
+            chainingMode = ChainingMode.ecb;\r
+        }\r
+        if (chainingMode != ChainingMode.ecb) {\r
+            throw new EncryptedDocumentException("Standard encryption only supports ECB chaining.");\r
+        }\r
+        if (keyBits == -1) {\r
+            keyBits = cipherAlgorithm.defaultKeySize;\r
+        }\r
+        if (blockSize == -1) {\r
+            blockSize = cipherAlgorithm.blockSize;\r
+        }\r
+        boolean found = false;\r
+        for (int ks : cipherAlgorithm.allowedKeySize) {\r
+            found |= (ks == keyBits);\r
+        }\r
+        if (!found) {\r
+            throw new EncryptedDocumentException("KeySize "+keyBits+" not allowed for Cipher "+cipherAlgorithm.toString());\r
+        }\r
+        header = new StandardEncryptionHeader(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);\r
+        verifier = new StandardEncryptionVerifier(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);\r
+        decryptor = new StandardDecryptor(info);\r
+        encryptor = new StandardEncryptor(this);\r
+    }\r
+\r
+    public StandardEncryptionHeader getHeader() {\r
+        return header;\r
+    }\r
+\r
+    public StandardEncryptionVerifier getVerifier() {\r
+        return verifier;\r
+    }\r
+\r
+    public StandardDecryptor getDecryptor() {\r
+        return decryptor;\r
+    }\r
+\r
+    public StandardEncryptor getEncryptor() {\r
+        return encryptor;\r
+    }\r
+    \r
+    public EncryptionInfo getEncryptionInfo() {\r
+        return info;\r
+    }\r
+}\r
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionVerifier.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptionVerifier.java
new file mode 100644 (file)
index 0000000..db93617
--- /dev/null
@@ -0,0 +1,112 @@
+/* ====================================================================
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================== */
+package org.apache.poi.poifs.crypt.standard;
+
+import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.poifs.crypt.ChainingMode;
+import org.apache.poi.poifs.crypt.CipherAlgorithm;
+import org.apache.poi.poifs.crypt.EncryptionVerifier;
+import org.apache.poi.poifs.crypt.HashAlgorithm;
+import org.apache.poi.poifs.filesystem.DocumentInputStream;
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;
+
+/**
+ * Used when checking if a key is valid for a document 
+ */
+public class StandardEncryptionVerifier extends EncryptionVerifier implements EncryptionRecord {
+    private static final int SPIN_COUNT = 50000;
+    private final int verifierHashSize;
+    
+    protected StandardEncryptionVerifier(DocumentInputStream is, StandardEncryptionHeader header) {
+        int saltSize = is.readInt();
+
+        if (saltSize!=16) {
+            throw new RuntimeException("Salt size != 16 !?");
+        }
+
+        byte salt[] = new byte[16];
+        is.readFully(salt);
+        setSalt(salt);
+        
+        byte encryptedVerifier[] = new byte[16];
+        is.readFully(encryptedVerifier);
+        setEncryptedVerifier(encryptedVerifier);
+
+        verifierHashSize = is.readInt();
+
+        byte encryptedVerifierHash[] = new byte[header.getCipherAlgorithm().encryptedVerifierHashLength];
+        is.readFully(encryptedVerifierHash);
+        setEncryptedVerifierHash(encryptedVerifierHash);
+
+        setSpinCount(SPIN_COUNT);
+        setCipherAlgorithm(CipherAlgorithm.aes128);
+        setChainingMode(ChainingMode.ecb);
+        setEncryptedKey(null);
+        setHashAlgorithm(HashAlgorithm.sha1); 
+    }
+    
+    protected StandardEncryptionVerifier(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {
+        setCipherAlgorithm(cipherAlgorithm);
+        setHashAlgorithm(hashAlgorithm);
+        setChainingMode(chainingMode);
+        setSpinCount(SPIN_COUNT);
+        verifierHashSize = hashAlgorithm.hashSize;
+    }
+
+    // make method visible for this package
+    protected void setSalt(byte salt[]) {
+        if (salt == null || salt.length != 16) {
+            throw new EncryptedDocumentException("invalid verifier salt");
+        }
+        super.setSalt(salt);
+    }
+    
+    // make method visible for this package
+    protected void setEncryptedVerifier(byte encryptedVerifier[]) {
+        super.setEncryptedVerifier(encryptedVerifier);
+    }
+
+    // make method visible for this package
+    protected void setEncryptedVerifierHash(byte encryptedVerifierHash[]) {
+        super.setEncryptedVerifierHash(encryptedVerifierHash);
+    }
+    
+    public void write(LittleEndianByteArrayOutputStream bos) {
+        // see [MS-OFFCRYPTO] - 2.3.4.9
+        byte salt[] = getSalt();
+        assert(salt.length == 16);
+        bos.writeInt(salt.length); // salt size
+        bos.write(salt);
+        
+        // The resulting Verifier value MUST be an array of 16 bytes.
+        byte encryptedVerifier[] = getEncryptedVerifier(); 
+        assert(encryptedVerifier.length == 16);
+        bos.write(encryptedVerifier);
+
+        // The number of bytes used by the encrypted Verifier hash MUST be 32.
+        // The number of bytes used by the decrypted Verifier hash is given by
+        // the VerifierHashSize field, which MUST be 20
+        byte encryptedVerifierHash[] = getEncryptedVerifierHash(); 
+        assert(encryptedVerifierHash.length == 32);
+        bos.writeInt(20);
+        bos.write(encryptedVerifierHash);
+    }
+
+    protected int getVerifierHashSize() {
+        return verifierHashSize;
+    }
+}
diff --git a/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java b/src/java/org/apache/poi/poifs/crypt/standard/StandardEncryptor.java
new file mode 100644 (file)
index 0000000..236eac1
--- /dev/null
@@ -0,0 +1,218 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt.standard;\r
+\r
+import static org.apache.poi.poifs.crypt.DataSpaceMapUtils.createEncryptionEntry;\r
+import static org.apache.poi.poifs.crypt.standard.StandardDecryptor.generateSecretKey;\r
+import static org.apache.poi.poifs.crypt.standard.StandardDecryptor.truncateOrPad;\r
+\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+import java.io.FilterOutputStream;\r
+import java.io.IOException;\r
+import java.io.OutputStream;\r
+import java.security.GeneralSecurityException;\r
+import java.security.MessageDigest;\r
+import java.security.SecureRandom;\r
+import java.util.Random;\r
+\r
+import javax.crypto.Cipher;\r
+import javax.crypto.CipherOutputStream;\r
+import javax.crypto.SecretKey;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.CryptoFunctions;\r
+import org.apache.poi.poifs.crypt.DataSpaceMapUtils;\r
+import org.apache.poi.poifs.crypt.EncryptionInfo;\r
+import org.apache.poi.poifs.crypt.EncryptionVerifier;\r
+import org.apache.poi.poifs.crypt.Encryptor;\r
+import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterEvent;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterListener;\r
+import org.apache.poi.util.IOUtils;\r
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
+import org.apache.poi.util.LittleEndianConsts;\r
+import org.apache.poi.util.LittleEndianOutputStream;\r
+import org.apache.poi.util.TempFile;\r
+\r
+public class StandardEncryptor extends Encryptor {\r
+    private final StandardEncryptionInfoBuilder builder;\r
+    \r
+    protected StandardEncryptor(StandardEncryptionInfoBuilder builder) {\r
+        this.builder = builder;\r
+    }    \r
+\r
+    public void confirmPassword(String password) {\r
+        // see [MS-OFFCRYPTO] - 2.3.3 EncryptionVerifier\r
+        Random r = new SecureRandom();\r
+        byte[] salt = new byte[16], verifier = new byte[16];\r
+        r.nextBytes(salt);\r
+        r.nextBytes(verifier);\r
+        \r
+        confirmPassword(password, null, null, salt, verifier, null);\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Fills the fields of verifier and header with the calculated hashes based\r
+     * on the password and a random salt\r
+     * \r
+     * see [MS-OFFCRYPTO] - 2.3.4.7 ECMA-376 Document Encryption Key Generation\r
+     */\r
+    public void confirmPassword(String password, byte keySpec[], byte keySalt[], byte verifier[], byte verifierSalt[], byte integritySalt[]) {\r
+        StandardEncryptionVerifier ver = builder.getVerifier();\r
+\r
+        ver.setSalt(verifierSalt);\r
+        SecretKey secretKey = generateSecretKey(password, ver, getKeySizeInBytes());\r
+        setSecretKey(secretKey);\r
+        Cipher cipher = getCipher(secretKey, null);\r
+        \r
+        try {\r
+            byte encryptedVerifier[] = cipher.doFinal(verifier); \r
+            MessageDigest hashAlgo = MessageDigest.getInstance(ver.getHashAlgorithm().jceId);\r
+            byte calcVerifierHash[] = hashAlgo.digest(verifier);\r
+            \r
+            // 2.3.3 EncryptionVerifier ...\r
+            // An array of bytes that contains the encrypted form of the \r
+            // hash of the randomly generated Verifier value. The length of the array MUST be the size of \r
+            // the encryption block size multiplied by the number of blocks needed to encrypt the hash of the \r
+            // Verifier. If the encryption algorithm is RC4, the length MUST be 20 bytes. If the encryption \r
+            // algorithm is AES, the length MUST be 32 bytes. After decrypting the EncryptedVerifierHash\r
+            // field, only the first VerifierHashSize bytes MUST be used.\r
+            int encVerHashSize = ver.getCipherAlgorithm().encryptedVerifierHashLength; \r
+            byte encryptedVerifierHash[] = cipher.doFinal(truncateOrPad(calcVerifierHash, encVerHashSize));\r
+    \r
+            ver.setEncryptedVerifier(encryptedVerifier);\r
+            ver.setEncryptedVerifierHash(encryptedVerifierHash);\r
+        } catch (GeneralSecurityException e) {\r
+            throw new EncryptedDocumentException("Password confirmation failed", e);\r
+        }\r
+        \r
+    }\r
+\r
+    private Cipher getCipher(SecretKey key, String padding) {\r
+        EncryptionVerifier ver = builder.getVerifier();\r
+        return CryptoFunctions.getCipher(key, ver.getCipherAlgorithm(), ver.getChainingMode(), null, Cipher.ENCRYPT_MODE, padding);\r
+    }\r
+    \r
+    public OutputStream getDataStream(final DirectoryNode dir)\r
+    throws IOException, GeneralSecurityException {\r
+        createEncryptionInfoEntry(dir);\r
+        DataSpaceMapUtils.addDefaultDataSpace(dir);\r
+        OutputStream countStream = new StandardCipherOutputStream(dir);\r
+        return countStream;\r
+    }\r
+    \r
+    protected class StandardCipherOutputStream extends FilterOutputStream implements POIFSWriterListener {\r
+        protected long countBytes;\r
+        protected final File fileOut;\r
+        protected final DirectoryNode dir;\r
+        \r
+        protected StandardCipherOutputStream(DirectoryNode dir) throws IOException {\r
+            super(null);\r
+\r
+            this.dir = dir;\r
+            fileOut = TempFile.createTempFile("encrypted_package", "crypt");\r
+            FileOutputStream rawStream = new FileOutputStream(fileOut);\r
+\r
+            // although not documented, we need the same padding as with agile encryption\r
+            // and instead of calculating the missing bytes for the block size ourselves\r
+            // we leave it up to the CipherOutputStream, which generates/saves them on close()\r
+            // ... we can't use "NoPadding" here\r
+            //\r
+            // see also [MS-OFFCRYPT] - 2.3.4.15\r
+            // The final data block MUST be padded to the next integral multiple of the\r
+            // KeyData.blockSize value. Any padding bytes can be used. Note that the StreamSize\r
+            // field of the EncryptedPackage field specifies the number of bytes of \r
+            // unencrypted data as specified in section 2.3.4.4.\r
+            CipherOutputStream cryptStream = new CipherOutputStream(rawStream, getCipher(getSecretKey(), "PKCS5Padding"));\r
+            \r
+            this.out = cryptStream;\r
+        }\r
+        \r
+        @Override\r
+        public void write(byte[] b, int off, int len) throws IOException {\r
+            out.write(b, off, len);\r
+            countBytes += len;\r
+        }\r
+\r
+        @Override\r
+        public void write(int b) throws IOException {\r
+            out.write(b);\r
+            countBytes++;\r
+        }\r
+    \r
+        public void close() throws IOException {\r
+            // the CipherOutputStream adds the padding bytes on close()\r
+            super.close(); \r
+            writeToPOIFS();\r
+        }\r
+        \r
+        void writeToPOIFS() throws IOException {\r
+            int oleStreamSize = (int)(fileOut.length()+LittleEndianConsts.LONG_SIZE);\r
+            dir.createDocument("EncryptedPackage", oleStreamSize, this);\r
+            // TODO: any properties???\r
+        }\r
+    \r
+        public void processPOIFSWriterEvent(POIFSWriterEvent event) {\r
+            try {\r
+                LittleEndianOutputStream leos = new LittleEndianOutputStream(event.getStream());\r
+\r
+                // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data \r
+                // encrypted within the EncryptedData field, not including the size of the StreamSize field. \r
+                // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this \r
+                // value, depending on the block size of the chosen encryption algorithm\r
+                leos.writeLong(countBytes);\r
+\r
+                FileInputStream fis = new FileInputStream(fileOut);\r
+                IOUtils.copy(fis, leos);\r
+                fis.close();\r
+                fileOut.delete();\r
+\r
+                leos.close();\r
+            } catch (IOException e) {\r
+                throw new EncryptedDocumentException(e);\r
+            }\r
+        }\r
+    }\r
+    \r
+    protected int getKeySizeInBytes() {\r
+        return builder.getHeader().getKeySize()/8;\r
+    }\r
+    \r
+    protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {\r
+        final EncryptionInfo info = builder.getEncryptionInfo();\r
+        final StandardEncryptionHeader header = builder.getHeader();\r
+        final StandardEncryptionVerifier verifier = builder.getVerifier();\r
+        \r
+        EncryptionRecord er = new EncryptionRecord(){\r
+            public void write(LittleEndianByteArrayOutputStream bos) {\r
+                bos.writeShort(info.getVersionMajor());\r
+                bos.writeShort(info.getVersionMinor());\r
+                bos.writeInt(info.getEncryptionFlags());\r
+                header.write(bos);\r
+                verifier.write(bos);\r
+            }\r
+        };\r
+        \r
+        createEncryptionEntry(dir, "EncryptionInfo", er);\r
+        \r
+        // TODO: any properties???\r
+    }\r
+}\r
index 0c5ad44a51c33aa97e40404e453ec49d69da79a2..82832ecff8a5f9e9e3ffd504a924dacbcaa84170 100644 (file)
@@ -21,6 +21,7 @@ package org.apache.poi;
  *
  * @author Yegor Kozlov
  */
+@SuppressWarnings("serial")
 public final class POIXMLException extends RuntimeException{
     /**
      * Create a new <code>POIXMLException</code> with no
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileDecryptor.java
new file mode 100644 (file)
index 0000000..7e45786
--- /dev/null
@@ -0,0 +1,404 @@
+/* ====================================================================
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================== */
+package org.apache.poi.poifs.crypt.agile;
+
+import static org.apache.poi.poifs.crypt.CryptoFunctions.generateIv;
+import static org.apache.poi.poifs.crypt.CryptoFunctions.generateKey;
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getBlock0;
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getCipher;
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest;
+import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.MessageDigest;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+
+import javax.crypto.Cipher;
+import javax.crypto.Mac;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.poifs.crypt.CipherAlgorithm;
+import org.apache.poi.poifs.crypt.CryptoFunctions;
+import org.apache.poi.poifs.crypt.Decryptor;
+import org.apache.poi.poifs.crypt.EncryptionHeader;
+import org.apache.poi.poifs.crypt.EncryptionVerifier;
+import org.apache.poi.poifs.crypt.HashAlgorithm;
+import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier.AgileCertificateEntry;
+import org.apache.poi.poifs.filesystem.DirectoryNode;
+import org.apache.poi.poifs.filesystem.DocumentInputStream;
+import org.apache.poi.util.LittleEndian;
+
+/**
+ * Decryptor implementation for Agile Encryption
+ */
+public class AgileDecryptor extends Decryptor {
+    private final AgileEncryptionInfoBuilder builder;
+    
+
+    private long _length = -1;
+
+    protected static final byte[] kVerifierInputBlock;
+    protected static final byte[] kHashedVerifierBlock;
+    protected static final byte[] kCryptoKeyBlock;
+    protected static final byte[] kIntegrityKeyBlock;
+    protected static final byte[] kIntegrityValueBlock;
+
+    static {
+        kVerifierInputBlock =
+            new byte[] { (byte)0xfe, (byte)0xa7, (byte)0xd2, (byte)0x76,
+                         (byte)0x3b, (byte)0x4b, (byte)0x9e, (byte)0x79 };
+        kHashedVerifierBlock =
+            new byte[] { (byte)0xd7, (byte)0xaa, (byte)0x0f, (byte)0x6d,
+                         (byte)0x30, (byte)0x61, (byte)0x34, (byte)0x4e };
+        kCryptoKeyBlock =
+            new byte[] { (byte)0x14, (byte)0x6e, (byte)0x0b, (byte)0xe7,
+                         (byte)0xab, (byte)0xac, (byte)0xd0, (byte)0xd6 };
+        kIntegrityKeyBlock =
+            new byte[] { (byte)0x5f, (byte)0xb2, (byte)0xad, (byte)0x01, 
+                         (byte)0x0c, (byte)0xb9, (byte)0xe1, (byte)0xf6 };
+        kIntegrityValueBlock =
+            new byte[] { (byte)0xa0, (byte)0x67, (byte)0x7f, (byte)0x02,
+                         (byte)0xb2, (byte)0x2c, (byte)0x84, (byte)0x33 };
+    }
+
+    protected AgileDecryptor(AgileEncryptionInfoBuilder builder) {
+        super(builder.getInfo());
+        this.builder = builder; 
+    }
+    
+    /**
+     * set decryption password
+     */
+    public boolean verifyPassword(String password) throws GeneralSecurityException {
+        AgileEncryptionVerifier ver = builder.getVerifier();
+        AgileEncryptionHeader header = builder.getHeader(); 
+        HashAlgorithm hashAlgo = header.getHashAlgorithmEx();
+        CipherAlgorithm cipherAlgo = header.getCipherAlgorithm();
+        int blockSize = header.getBlockSize();
+        int keySize = header.getKeySize()/8;
+
+        byte[] pwHash = hashPassword(password, ver.getHashAlgorithm(), ver.getSalt(), ver.getSpinCount());
+
+        /**
+         * encryptedVerifierHashInput: This attribute MUST be generated by using the following steps:
+         * 1. Generate a random array of bytes with the number of bytes used specified by the saltSize
+         *    attribute.
+         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
+         *    consisting of the following bytes: 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, and 0x79.
+         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue
+         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an
+         *    integral multiple of blockSize bytes, pad the array with 0x00 to the next integral multiple of
+         *    blockSize bytes.
+         * 4. Use base64 to encode the result of step 3.
+         */
+        byte verfierInputEnc[] = hashInput(builder, pwHash, kVerifierInputBlock, ver.getEncryptedVerifier(), Cipher.DECRYPT_MODE);
+        setVerifier(verfierInputEnc);
+        MessageDigest hashMD = getMessageDigest(hashAlgo);
+        byte[] verifierHash = hashMD.digest(verfierInputEnc);
+
+        /**
+         * encryptedVerifierHashValue: This attribute MUST be generated by using the following steps:
+         * 1. Obtain the hash value of the random array of bytes generated in step 1 of the steps for
+         *    encryptedVerifierHashInput.
+         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
+         *    consisting of the following bytes: 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, and 0x4e.
+         * 3. Encrypt the hash value obtained in step 1 by using the binary form of the saltValue attribute as
+         *    an initialization vector as specified in section 2.3.4.12. If hashSize is not an integral multiple of
+         *    blockSize bytes, pad the hash value with 0x00 to an integral multiple of blockSize bytes.
+         * 4. Use base64 to encode the result of step 3.
+         */
+        byte verifierHashDec[] = hashInput(builder, pwHash, kHashedVerifierBlock, ver.getEncryptedVerifierHash(), Cipher.DECRYPT_MODE);
+        verifierHashDec = getBlock0(verifierHashDec, hashAlgo.hashSize);
+        
+        /**
+         * encryptedKeyValue: This attribute MUST be generated by using the following steps:
+         * 1. Generate a random array of bytes that is the same size as specified by the
+         *    Encryptor.KeyData.keyBits attribute of the parent element.
+         * 2. Generate an encryption key as specified in section 2.3.4.11, using the user-supplied password,
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array
+         *    consisting of the following bytes: 0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, and 0xd6.
+         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue
+         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an
+         *    integral multiple of blockSize bytes, pad the array with 0x00 to an integral multiple of
+         *    blockSize bytes.
+         * 4. Use base64 to encode the result of step 3.
+         */
+        byte keyspec[] = hashInput(builder, pwHash, kCryptoKeyBlock, ver.getEncryptedKey(), Cipher.DECRYPT_MODE);
+        keyspec = getBlock0(keyspec, keySize);
+        SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.getCipherAlgorithm().jceId);
+
+        /**
+         * 1. Obtain the intermediate key by decrypting the encryptedKeyValue from a KeyEncryptor
+         *    contained within the KeyEncryptors sequence. Use this key for encryption operations in the
+         *    remaining steps of this section.
+         * 2. Generate a random array of bytes, known as Salt, of the same length as the value of the
+         *    KeyData.hashSize attribute.
+         * 3. Encrypt the random array of bytes generated in step 2 by using the binary form of the
+         *    KeyData.saltValue attribute and a blockKey byte array consisting of the following bytes: 0x5f,
+         *    0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, and 0xf6 used to form an initialization vector as specified in
+         *    section 2.3.4.12. If the array of bytes is not an integral multiple of blockSize bytes, pad the
+         *    array with 0x00 to the next integral multiple of blockSize bytes.
+         * 4. Assign the encryptedHmacKey attribute to the base64-encoded form of the result of step 3.
+         */
+        byte vec[] = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityKeyBlock, blockSize); 
+        Cipher cipher = getCipher(secretKey, cipherAlgo, ver.getChainingMode(), vec, Cipher.DECRYPT_MODE);
+        byte hmacKey[] = cipher.doFinal(header.getEncryptedHmacKey());
+        hmacKey = getBlock0(hmacKey, hashAlgo.hashSize);
+
+        /**
+         * 5. Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message),
+         *    which the DataIntegrity element will verify by using the Salt generated in step 2 as the key.
+         *    Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be
+         *    used as the message.
+         * 6. Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes:
+         *    0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33.
+         * 7. Assign the encryptedHmacValue attribute to the base64-encoded form of the result of step 6.
+         */
+        vec = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityValueBlock, blockSize);
+        cipher = getCipher(secretKey, cipherAlgo, ver.getChainingMode(), vec, Cipher.DECRYPT_MODE);
+        byte hmacValue[] = cipher.doFinal(header.getEncryptedHmacValue());
+        hmacValue = getBlock0(hmacValue, hashAlgo.hashSize);
+        
+        if (Arrays.equals(verifierHashDec, verifierHash)) {
+            setSecretKey(secretKey);
+            setIntegrityHmacKey(hmacKey);
+            setIntegrityHmacValue(hmacValue);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * instead of a password, it's also possible to decrypt via certificate.
+     * Warning: this code is experimental and hasn't been validated
+     * 
+     * {@linkplain http://social.msdn.microsoft.com/Forums/en-US/cc9092bb-0c82-4b5b-ae21-abf643bdb37c/agile-encryption-with-certificates}
+     *
+     * @param keyPair
+     * @param x509
+     * @return
+     * @throws GeneralSecurityException
+     */
+    public boolean verifyPassword(KeyPair keyPair, X509Certificate x509) throws GeneralSecurityException {
+        AgileEncryptionVerifier ver = builder.getVerifier();
+        AgileEncryptionHeader header = builder.getHeader();
+        HashAlgorithm hashAlgo = header.getHashAlgorithmEx();
+        CipherAlgorithm cipherAlgo = header.getCipherAlgorithm();
+        int blockSize = header.getBlockSize();
+        
+        AgileCertificateEntry ace = null;
+        for (AgileCertificateEntry aceEntry : ver.getCertificates()) {
+            if (x509.equals(aceEntry.x509)) {
+                ace = aceEntry;
+                break;
+            }
+        }
+        if (ace == null) return false;
+        
+        Cipher cipher = Cipher.getInstance("RSA");
+        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
+        byte keyspec[] = cipher.doFinal(ace.encryptedKey);
+        SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.getCipherAlgorithm().jceId);
+        
+        Mac x509Hmac = CryptoFunctions.getMac(hashAlgo);
+        x509Hmac.init(secretKey);
+        byte certVerifier[] = x509Hmac.doFinal(ace.x509.getEncoded());
+
+        byte vec[] = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityKeyBlock, blockSize); 
+        cipher = getCipher(secretKey, cipherAlgo, ver.getChainingMode(), vec, Cipher.DECRYPT_MODE);
+        byte hmacKey[] = cipher.doFinal(header.getEncryptedHmacKey());
+        hmacKey = getBlock0(hmacKey, hashAlgo.hashSize);
+
+        vec = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityValueBlock, blockSize);
+        cipher = getCipher(secretKey, cipherAlgo, ver.getChainingMode(), vec, Cipher.DECRYPT_MODE);
+        byte hmacValue[] = cipher.doFinal(header.getEncryptedHmacValue());
+        hmacValue = getBlock0(hmacValue, hashAlgo.hashSize);
+        
+        
+        if (Arrays.equals(ace.certVerifier, certVerifier)) {
+            setSecretKey(secretKey);
+            setIntegrityHmacKey(hmacKey);
+            setIntegrityHmacValue(hmacValue);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    protected static int getNextBlockSize(int inputLen, int blockSize) {
+        int fillSize;
+        for (fillSize=blockSize; fillSize<inputLen; fillSize+=blockSize);
+        return fillSize;
+    }
+
+    protected static byte[] hashInput(AgileEncryptionInfoBuilder builder, byte pwHash[], byte blockKey[], byte inputKey[], int cipherMode) {
+        EncryptionVerifier ver = builder.getVerifier();
+        int keySize = builder.getDecryptor().getKeySizeInBytes();
+        int blockSize = builder.getDecryptor().getBlockSizeInBytes();
+        HashAlgorithm hashAlgo = ver.getHashAlgorithm();
+        byte[] salt = ver.getSalt();
+
+        byte intermedKey[] = generateKey(pwHash, hashAlgo, blockKey, keySize);
+        SecretKey skey = new SecretKeySpec(intermedKey, ver.getCipherAlgorithm().jceId);
+        byte[] iv = generateIv(hashAlgo, salt, null, blockSize);
+        Cipher cipher = getCipher(skey, ver.getCipherAlgorithm(), ver.getChainingMode(), iv, cipherMode);
+        byte[] hashFinal;
+        
+        try {
+            inputKey = getBlock0(inputKey, getNextBlockSize(inputKey.length, blockSize));
+            hashFinal = cipher.doFinal(inputKey);
+            return hashFinal;
+        } catch (GeneralSecurityException e) {
+            throw new EncryptedDocumentException(e);
+        }
+    }
+
+    public InputStream getDataStream(DirectoryNode dir) throws IOException, GeneralSecurityException {
+        DocumentInputStream dis = dir.createDocumentInputStream("EncryptedPackage");
+        _length = dis.readLong();
+        
+        ChunkedCipherInputStream cipherStream = new ChunkedCipherInputStream(dis, _length);
+        return cipherStream;
+    }
+
+    public long getLength(){
+        if(_length == -1) throw new IllegalStateException("EcmaDecryptor.getDataStream() was not called");
+        return _length;
+    }
+
+    /**
+     * 2.3.4.15 Data Encryption (Agile Encryption)
+     * 
+     * The EncryptedPackage stream (1) MUST be encrypted in 4096-byte segments to facilitate nearly
+     * random access while allowing CBC modes to be used in the encryption process.
+     * The initialization vector for the encryption process MUST be obtained by using the zero-based
+     * segment number as a blockKey and the binary form of the KeyData.saltValue as specified in
+     * section 2.3.4.12. The block number MUST be represented as a 32-bit unsigned integer.
+     * Data blocks MUST then be encrypted by using the initialization vector and the intermediate key
+     * obtained by decrypting the encryptedKeyValue from a KeyEncryptor contained within the
+     * KeyEncryptors sequence as specified in section 2.3.4.10. The final data block MUST be padded to
+     * the next integral multiple of the KeyData.blockSize value. Any padding bytes can be used. Note
+     * that the StreamSize field of the EncryptedPackage field specifies the number of bytes of
+     * unencrypted data as specified in section 2.3.4.4.
+     */
+    private class ChunkedCipherInputStream extends InputStream {
+        private int _lastIndex = 0;
+        private long _pos = 0;
+        private final long _size;
+        private final InputStream _stream;
+        private byte[] _chunk;
+        private Cipher _cipher;
+
+        public ChunkedCipherInputStream(DocumentInputStream stream, long size)
+            throws GeneralSecurityException {
+            EncryptionHeader header = info.getHeader();
+            _size = size;
+            _stream = stream;
+            _cipher = getCipher(getSecretKey(), header.getCipherAlgorithm(), header.getChainingMode(), header.getKeySalt(), Cipher.DECRYPT_MODE);
+        }
+
+        public int read() throws IOException {
+            byte[] b = new byte[1];
+            if (read(b) == 1)
+                return b[0];
+            return -1;
+        }
+
+        public int read(byte[] b) throws IOException {
+            return read(b, 0, b.length);
+        }
+
+        public int read(byte[] b, int off, int len) throws IOException {
+            int total = 0;
+            
+            if (available() <= 0) return -1;
+
+            while (len > 0) {
+                if (_chunk == null) {
+                    try {
+                        _chunk = nextChunk();
+                    } catch (GeneralSecurityException e) {
+                        throw new EncryptedDocumentException(e.getMessage());
+                    }
+                }
+                int count = (int)(4096L - (_pos & 0xfff));
+                int avail = available();
+                if (avail == 0) {
+                    return total;
+                }
+                count = Math.min(avail, Math.min(count, len));
+                System.arraycopy(_chunk, (int)(_pos & 0xfff), b, off, count);
+                off += count;
+                len -= count;
+                _pos += count;
+                if ((_pos & 0xfff) == 0)
+                    _chunk = null;
+                total += count;
+            }
+
+            return total;
+        }
+
+        public long skip(long n) throws IOException {
+            long start = _pos;
+            long skip = Math.min(available(), n);
+
+            if ((((_pos + skip) ^ start) & ~0xfff) != 0)
+                _chunk = null;
+            _pos += skip;
+            return skip;
+        }
+
+        public int available() throws IOException { return (int)(_size - _pos); }
+        public void close() throws IOException { _stream.close(); }
+        public boolean markSupported() { return false; }
+
+        private byte[] nextChunk() throws GeneralSecurityException, IOException {
+            int index = (int)(_pos >> 12);
+            byte[] blockKey = new byte[4];
+            LittleEndian.putInt(blockKey, 0, index);
+            EncryptionHeader header = info.getHeader();
+            byte[] iv = generateIv(header.getHashAlgorithmEx(), header.getKeySalt(), blockKey, getBlockSizeInBytes());
+            _cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), new IvParameterSpec(iv));
+            if (_lastIndex != index)
+                _stream.skip((index - _lastIndex) << 12);
+
+            byte[] block = new byte[Math.min(_stream.available(), 4096)];
+            _stream.read(block);
+            _lastIndex = index + 1;
+            return _cipher.doFinal(block);
+        }
+    }
+
+    protected int getBlockSizeInBytes() {
+       return info.getHeader().getBlockSize();
+    }
+    
+    protected int getKeySizeInBytes() {
+       return info.getHeader().getKeySize()/8;
+    }
+}
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionHeader.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionHeader.java
new file mode 100644 (file)
index 0000000..965207e
--- /dev/null
@@ -0,0 +1,130 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.agile;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.ChainingMode;\r
+import org.apache.poi.poifs.crypt.CipherAlgorithm;\r
+import org.apache.poi.poifs.crypt.EncryptionHeader;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
+import org.apache.xmlbeans.XmlException;\r
+\r
+import com.microsoft.schemas.office.x2006.encryption.CTDataIntegrity;\r
+import com.microsoft.schemas.office.x2006.encryption.CTKeyData;\r
+import com.microsoft.schemas.office.x2006.encryption.EncryptionDocument;\r
+import com.microsoft.schemas.office.x2006.encryption.STCipherChaining;\r
+\r
+public class AgileEncryptionHeader extends EncryptionHeader {\r
+    private byte encryptedHmacKey[], encryptedHmacValue[];\r
+    \r
+    public AgileEncryptionHeader(String descriptor) throws IOException {\r
+        EncryptionDocument ed;\r
+        try {\r
+            ed = EncryptionDocument.Factory.parse(descriptor);\r
+        } catch (XmlException e) {\r
+            throw new EncryptedDocumentException("Unable to parse encryption descriptor", e);\r
+        }\r
+        \r
+        CTKeyData keyData;\r
+        try {\r
+            keyData = ed.getEncryption().getKeyData();\r
+            if (keyData == null) {\r
+                throw new NullPointerException("keyData not set");\r
+            }\r
+        } catch (Exception e) {\r
+            throw new EncryptedDocumentException("Unable to parse keyData");\r
+        }\r
+\r
+        setKeySize((int)keyData.getKeyBits());\r
+        setFlags(0);\r
+        setSizeExtra(0);\r
+        setCspName(null);\r
+        setBlockSize(keyData.getBlockSize());\r
+\r
+        int keyBits = (int)keyData.getKeyBits();\r
+        \r
+        CipherAlgorithm ca = CipherAlgorithm.fromXmlId(keyData.getCipherAlgorithm().toString(), keyBits);\r
+        setCipherAlgorithm(ca);\r
+        setCipherProvider(ca.provider);\r
+\r
+        switch (keyData.getCipherChaining().intValue()) {\r
+        case STCipherChaining.INT_CHAINING_MODE_CBC:\r
+            setChainingMode(ChainingMode.cbc);\r
+            break;\r
+        case STCipherChaining.INT_CHAINING_MODE_CFB:\r
+            setChainingMode(ChainingMode.cfb);\r
+            break;\r
+        default:\r
+            throw new EncryptedDocumentException("Unsupported chaining mode - "+keyData.getCipherChaining().toString());\r
+        }\r
+    \r
+        int hashSize = keyData.getHashSize();\r
+        \r
+        HashAlgorithm ha = HashAlgorithm.fromEcmaId(keyData.getHashAlgorithm().toString());\r
+        setHashAlgorithm(ha);\r
+\r
+        if (getHashAlgorithmEx().hashSize != hashSize) {\r
+            throw new EncryptedDocumentException("Unsupported hash algorithm: " + \r
+                    keyData.getHashAlgorithm() + " @ " + hashSize + " bytes");\r
+        }\r
+\r
+        int saltLength = keyData.getSaltSize();\r
+        setKeySalt(keyData.getSaltValue());\r
+        if (getKeySalt().length != saltLength) {\r
+            throw new EncryptedDocumentException("Invalid salt length");\r
+        }\r
+        \r
+        CTDataIntegrity di = ed.getEncryption().getDataIntegrity();\r
+        setEncryptedHmacKey(di.getEncryptedHmacKey());\r
+        setEncryptedHmacValue(di.getEncryptedHmacValue());\r
+    }\r
+    \r
+    \r
+    public AgileEncryptionHeader(CipherAlgorithm algorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {\r
+        setCipherAlgorithm(algorithm);\r
+        setHashAlgorithm(hashAlgorithm);\r
+        setKeySize(keyBits);\r
+        setBlockSize(blockSize);\r
+        setChainingMode(chainingMode);\r
+    }\r
+\r
+    // make method visible for this package\r
+    protected void setKeySalt(byte salt[]) {\r
+        if (salt == null || salt.length != getBlockSize()) {\r
+            throw new EncryptedDocumentException("invalid verifier salt");\r
+        }\r
+        super.setKeySalt(salt);\r
+    }\r
+\r
+    public byte[] getEncryptedHmacKey() {\r
+        return encryptedHmacKey;\r
+    }\r
+\r
+    protected void setEncryptedHmacKey(byte[] encryptedHmacKey) {\r
+        this.encryptedHmacKey = encryptedHmacKey;\r
+    }\r
+\r
+    public byte[] getEncryptedHmacValue() {\r
+        return encryptedHmacValue;\r
+    }\r
+\r
+    protected void setEncryptedHmacValue(byte[] encryptedHmacValue) {\r
+        this.encryptedHmacValue = encryptedHmacValue;\r
+    }\r
+}\r
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionInfoBuilder.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionInfoBuilder.java
new file mode 100644 (file)
index 0000000..12a7462
--- /dev/null
@@ -0,0 +1,111 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.agile;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.ChainingMode;\r
+import org.apache.poi.poifs.crypt.CipherAlgorithm;\r
+import org.apache.poi.poifs.crypt.EncryptionInfo;\r
+import org.apache.poi.poifs.crypt.EncryptionInfoBuilder;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
+import org.apache.poi.poifs.filesystem.DocumentInputStream;\r
+\r
+public class AgileEncryptionInfoBuilder implements EncryptionInfoBuilder {\r
+    \r
+    EncryptionInfo info;\r
+    AgileEncryptionHeader header;\r
+    AgileEncryptionVerifier verifier;\r
+    AgileDecryptor decryptor;\r
+    AgileEncryptor encryptor;\r
+\r
+    public void initialize(EncryptionInfo info, DocumentInputStream dis) throws IOException {\r
+        this.info = info;\r
+        \r
+        StringBuilder builder = new StringBuilder();\r
+        byte[] xmlDescriptor = new byte[dis.available()];\r
+        dis.read(xmlDescriptor);\r
+        for (byte b : xmlDescriptor)\r
+            builder.append((char)b);\r
+        String descriptor = builder.toString();\r
+        header = new AgileEncryptionHeader(descriptor);\r
+        verifier = new AgileEncryptionVerifier(descriptor);\r
+        if (info.getVersionMajor() == 4 && info.getVersionMinor() == 4) {\r
+            decryptor = new AgileDecryptor(this);\r
+        }\r
+    }\r
+\r
+    public void initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {\r
+        this.info = info;\r
+\r
+        if (cipherAlgorithm == null) {\r
+            cipherAlgorithm = CipherAlgorithm.aes128;\r
+        }\r
+        if (cipherAlgorithm == CipherAlgorithm.rc4) {\r
+            throw new EncryptedDocumentException("RC4 must not be used with agile encryption.");\r
+        }\r
+        if (hashAlgorithm == null) {\r
+            hashAlgorithm = HashAlgorithm.sha1;\r
+        }\r
+        if (chainingMode == null) {\r
+            chainingMode = ChainingMode.cbc;\r
+        }\r
+        if (!(chainingMode == ChainingMode.cbc || chainingMode == ChainingMode.cfb)) {\r
+            throw new EncryptedDocumentException("Agile encryption only supports CBC/CFB chaining.");\r
+        }\r
+        if (keyBits == -1) {\r
+            keyBits = cipherAlgorithm.defaultKeySize;\r
+        }\r
+        if (blockSize == -1) {\r
+            blockSize = cipherAlgorithm.blockSize;\r
+        }\r
+        boolean found = false;\r
+        for (int ks : cipherAlgorithm.allowedKeySize) {\r
+            found |= (ks == keyBits);\r
+        }\r
+        if (!found) {\r
+            throw new EncryptedDocumentException("KeySize "+keyBits+" not allowed for Cipher "+cipherAlgorithm.toString());\r
+        }\r
+        header = new AgileEncryptionHeader(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);\r
+        verifier = new AgileEncryptionVerifier(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode);\r
+        decryptor = new AgileDecryptor(this);\r
+        encryptor = new AgileEncryptor(this);\r
+    }\r
+    \r
+    public AgileEncryptionHeader getHeader() {\r
+        return header;\r
+    }\r
+\r
+    public AgileEncryptionVerifier getVerifier() {\r
+        return verifier;\r
+    }\r
+\r
+    public AgileDecryptor getDecryptor() {\r
+        return decryptor;\r
+    }\r
+\r
+    public AgileEncryptor getEncryptor() {\r
+        return encryptor;\r
+    }\r
+\r
+    protected EncryptionInfo getInfo() {\r
+        return info;\r
+    }\r
+    \r
+    \r
+}\r
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionVerifier.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptionVerifier.java
new file mode 100644 (file)
index 0000000..b3d2494
--- /dev/null
@@ -0,0 +1,164 @@
+/* ====================================================================
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+==================================================================== */
+package org.apache.poi.poifs.crypt.agile;
+
+import java.io.ByteArrayInputStream;
+import java.security.GeneralSecurityException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.poi.EncryptedDocumentException;
+import org.apache.poi.poifs.crypt.ChainingMode;
+import org.apache.poi.poifs.crypt.CipherAlgorithm;
+import org.apache.poi.poifs.crypt.EncryptionVerifier;
+import org.apache.poi.poifs.crypt.HashAlgorithm;
+import org.apache.xmlbeans.XmlException;
+
+import com.microsoft.schemas.office.x2006.encryption.CTKeyEncryptor;
+import com.microsoft.schemas.office.x2006.encryption.EncryptionDocument;
+import com.microsoft.schemas.office.x2006.encryption.STCipherChaining;
+import com.microsoft.schemas.office.x2006.keyEncryptor.certificate.CTCertificateKeyEncryptor;
+import com.microsoft.schemas.office.x2006.keyEncryptor.password.CTPasswordKeyEncryptor;
+
+/**
+ * Used when checking if a key is valid for a document 
+ */
+public class AgileEncryptionVerifier extends EncryptionVerifier {
+
+    public static class AgileCertificateEntry {
+        X509Certificate x509;
+        byte encryptedKey[];
+        byte certVerifier[];
+    }
+    
+    private List<AgileCertificateEntry> certList = new ArrayList<AgileCertificateEntry>();
+
+    
+    public AgileEncryptionVerifier(String descriptor) {
+        EncryptionDocument ed;
+        try {
+            ed = EncryptionDocument.Factory.parse(descriptor);
+        } catch (XmlException e) {
+            throw new EncryptedDocumentException("Unable to parse encryption descriptor", e);
+        }
+
+        Iterator<CTKeyEncryptor> encList = ed.getEncryption().getKeyEncryptors().getKeyEncryptorList().iterator();
+        CTPasswordKeyEncryptor keyData;
+        try {
+            keyData = encList.next().getEncryptedPasswordKey();
+            if (keyData == null) {
+                throw new NullPointerException("encryptedKey not set");
+            }
+        } catch (Exception e) {
+            throw new EncryptedDocumentException("Unable to parse keyData", e);
+        }
+        
+        int keyBits = (int)keyData.getKeyBits();
+        
+        CipherAlgorithm ca = CipherAlgorithm.fromXmlId(keyData.getCipherAlgorithm().toString(), keyBits);
+        setCipherAlgorithm(ca);
+
+        int hashSize = keyData.getHashSize();
+
+        HashAlgorithm ha = HashAlgorithm.fromEcmaId(keyData.getHashAlgorithm().toString());
+        setHashAlgorithm(ha);
+
+        if (getHashAlgorithm().hashSize != hashSize) {
+            throw new EncryptedDocumentException("Unsupported hash algorithm: " + 
+                    keyData.getHashAlgorithm() + " @ " + hashSize + " bytes");
+        }
+
+        setSpinCount(keyData.getSpinCount());
+        setEncryptedVerifier(keyData.getEncryptedVerifierHashInput());
+        setSalt(keyData.getSaltValue());
+        setEncryptedKey(keyData.getEncryptedKeyValue()); 
+        setEncryptedVerifierHash(keyData.getEncryptedVerifierHashValue());
+
+        int saltSize = keyData.getSaltSize();
+        if (saltSize != getSalt().length)
+            throw new EncryptedDocumentException("Invalid salt size");
+        
+        switch (keyData.getCipherChaining().intValue()) {
+            case STCipherChaining.INT_CHAINING_MODE_CBC:
+                setChainingMode(ChainingMode.cbc);
+                break;
+            case STCipherChaining.INT_CHAINING_MODE_CFB:
+                setChainingMode(ChainingMode.cfb);
+                break;
+            default:
+                throw new EncryptedDocumentException("Unsupported chaining mode - "+keyData.getCipherChaining().toString());
+        }
+        
+        if (!encList.hasNext()) return;
+        
+        try {
+            CertificateFactory cf = CertificateFactory.getInstance("X.509");
+            while (encList.hasNext()) {
+                CTCertificateKeyEncryptor certKey = encList.next().getEncryptedCertificateKey();
+                AgileCertificateEntry ace = new AgileCertificateEntry();
+                ace.certVerifier = certKey.getCertVerifier();
+                ace.encryptedKey = certKey.getEncryptedKeyValue();
+                ace.x509 = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certKey.getX509Certificate()));
+                certList.add(ace);
+            }
+        } catch (GeneralSecurityException e) {
+            throw new EncryptedDocumentException("can't parse X509 certificate", e);
+        }
+    }
+    
+    public AgileEncryptionVerifier(CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {
+        setCipherAlgorithm(cipherAlgorithm);
+        setHashAlgorithm(hashAlgorithm);
+        setChainingMode(chainingMode);
+        setSpinCount(100000); // TODO: use parameter
+    }
+    
+    protected void setSalt(byte salt[]) {
+        if (salt == null || salt.length != getCipherAlgorithm().blockSize) {
+            throw new EncryptedDocumentException("invalid verifier salt");
+        }
+        super.setSalt(salt);
+    }
+    
+    // make method visible for this package
+    protected void setEncryptedVerifier(byte encryptedVerifier[]) {
+        super.setEncryptedVerifier(encryptedVerifier);
+    }
+
+    // make method visible for this package
+    protected void setEncryptedVerifierHash(byte encryptedVerifierHash[]) {
+        super.setEncryptedVerifierHash(encryptedVerifierHash);
+    }
+
+    // make method visible for this package
+    protected void setEncryptedKey(byte[] encryptedKey) {
+        super.setEncryptedKey(encryptedKey);
+    }
+    
+    public void addCertificate(X509Certificate x509) {
+        AgileCertificateEntry ace = new AgileCertificateEntry();
+        ace.x509 = x509;
+        certList.add(ace);
+    }
+    
+    public List<AgileCertificateEntry> getCertificates() {
+        return certList;
+    }
+}
diff --git a/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java b/src/ooxml/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java
new file mode 100644 (file)
index 0000000..558d07e
--- /dev/null
@@ -0,0 +1,511 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt.agile;\r
+\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.generateIv;\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getBlock0;\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getCipher;\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.getMessageDigest;\r
+import static org.apache.poi.poifs.crypt.CryptoFunctions.hashPassword;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.getNextBlockSize;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.hashInput;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kCryptoKeyBlock;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kHashedVerifierBlock;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kIntegrityKeyBlock;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kIntegrityValueBlock;\r
+import static org.apache.poi.poifs.crypt.agile.AgileDecryptor.kVerifierInputBlock;\r
+\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileOutputStream;\r
+import java.io.FilterOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.security.GeneralSecurityException;\r
+import java.security.MessageDigest;\r
+import java.security.SecureRandom;\r
+import java.security.cert.CertificateEncodingException;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import java.util.Random;\r
+\r
+import javax.crypto.Cipher;\r
+import javax.crypto.Mac;\r
+import javax.crypto.SecretKey;\r
+import javax.crypto.spec.IvParameterSpec;\r
+import javax.crypto.spec.SecretKeySpec;\r
+\r
+import org.apache.poi.EncryptedDocumentException;\r
+import org.apache.poi.poifs.crypt.CryptoFunctions;\r
+import org.apache.poi.poifs.crypt.DataSpaceMapUtils;\r
+import org.apache.poi.poifs.crypt.EncryptionHeader;\r
+import org.apache.poi.poifs.crypt.EncryptionInfo;\r
+import org.apache.poi.poifs.crypt.Encryptor;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
+import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier.AgileCertificateEntry;\r
+import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterEvent;\r
+import org.apache.poi.poifs.filesystem.POIFSWriterListener;\r
+import org.apache.poi.util.IOUtils;\r
+import org.apache.poi.util.LittleEndian;\r
+import org.apache.poi.util.LittleEndianByteArrayOutputStream;\r
+import org.apache.poi.util.LittleEndianConsts;\r
+import org.apache.poi.util.LittleEndianOutputStream;\r
+import org.apache.poi.util.TempFile;\r
+import org.apache.xmlbeans.XmlOptions;\r
+\r
+import com.microsoft.schemas.office.x2006.encryption.CTDataIntegrity;\r
+import com.microsoft.schemas.office.x2006.encryption.CTEncryption;\r
+import com.microsoft.schemas.office.x2006.encryption.CTKeyData;\r
+import com.microsoft.schemas.office.x2006.encryption.CTKeyEncryptor;\r
+import com.microsoft.schemas.office.x2006.encryption.CTKeyEncryptors;\r
+import com.microsoft.schemas.office.x2006.encryption.EncryptionDocument;\r
+import com.microsoft.schemas.office.x2006.encryption.STCipherAlgorithm;\r
+import com.microsoft.schemas.office.x2006.encryption.STCipherChaining;\r
+import com.microsoft.schemas.office.x2006.encryption.STHashAlgorithm;\r
+import com.microsoft.schemas.office.x2006.keyEncryptor.certificate.CTCertificateKeyEncryptor;\r
+import com.microsoft.schemas.office.x2006.keyEncryptor.password.CTPasswordKeyEncryptor;\r
+\r
+public class AgileEncryptor extends Encryptor {\r
+    private final AgileEncryptionInfoBuilder builder;\r
+    @SuppressWarnings("unused")\r
+    private byte integritySalt[];\r
+    private Mac integrityMD;\r
+       private byte pwHash[];\r
+    \r
+       protected AgileEncryptor(AgileEncryptionInfoBuilder builder) {\r
+               this.builder = builder;\r
+       }\r
+\r
+    public void confirmPassword(String password) {\r
+        // see [MS-OFFCRYPTO] - 2.3.3 EncryptionVerifier\r
+        Random r = new SecureRandom();\r
+        int blockSize = builder.getHeader().getBlockSize();\r
+        int keySize = builder.getHeader().getKeySize()/8;\r
+        int hashSize = builder.getHeader().getHashAlgorithmEx().hashSize;\r
+        \r
+        byte[] verifierSalt = new byte[blockSize]\r
+             , verifier = new byte[blockSize]\r
+             , keySalt = new byte[blockSize]\r
+             , keySpec = new byte[keySize]\r
+             , integritySalt = new byte[hashSize];\r
+        r.nextBytes(verifierSalt); // blocksize\r
+        r.nextBytes(verifier); // blocksize\r
+        r.nextBytes(keySalt); // blocksize\r
+        r.nextBytes(keySpec); // keysize\r
+        r.nextBytes(integritySalt); // hashsize\r
+        \r
+        confirmPassword(password, keySpec, keySalt, verifierSalt, verifier, integritySalt);\r
+    }\r
+       \r
+       public void confirmPassword(String password, byte keySpec[], byte keySalt[], byte verifier[], byte verifierSalt[], byte integritySalt[]) {\r
+        AgileEncryptionVerifier ver = builder.getVerifier();\r
+        ver.setSalt(verifierSalt);\r
+        AgileEncryptionHeader header = builder.getHeader();\r
+        header.setKeySalt(keySalt);\r
+        HashAlgorithm hashAlgo = ver.getHashAlgorithm();\r
+\r
+        int blockSize = header.getBlockSize();\r
+           \r
+        pwHash = hashPassword(password, hashAlgo, verifierSalt, ver.getSpinCount());\r
+        \r
+        /**\r
+         * encryptedVerifierHashInput: This attribute MUST be generated by using the following steps:\r
+         * 1. Generate a random array of bytes with the number of bytes used specified by the saltSize\r
+         *    attribute.\r
+         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,\r
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array\r
+         *    consisting of the following bytes: 0xfe, 0xa7, 0xd2, 0x76, 0x3b, 0x4b, 0x9e, and 0x79.\r
+         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue\r
+         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an\r
+         *    integral multiple of blockSize bytes, pad the array with 0x00 to the next integral multiple of\r
+         *    blockSize bytes.\r
+         * 4. Use base64 to encode the result of step 3.\r
+         */\r
+        byte encryptedVerifier[] = hashInput(builder, pwHash, kVerifierInputBlock, verifier, Cipher.ENCRYPT_MODE);\r
+        ver.setEncryptedVerifier(encryptedVerifier);\r
+           \r
+\r
+        /**\r
+         * encryptedVerifierHashValue: This attribute MUST be generated by using the following steps:\r
+         * 1. Obtain the hash value of the random array of bytes generated in step 1 of the steps for\r
+         *    encryptedVerifierHashInput.\r
+         * 2. Generate an encryption key as specified in section 2.3.4.11 by using the user-supplied password,\r
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array\r
+         *    consisting of the following bytes: 0xd7, 0xaa, 0x0f, 0x6d, 0x30, 0x61, 0x34, and 0x4e.\r
+         * 3. Encrypt the hash value obtained in step 1 by using the binary form of the saltValue attribute as\r
+         *    an initialization vector as specified in section 2.3.4.12. If hashSize is not an integral multiple of\r
+         *    blockSize bytes, pad the hash value with 0x00 to an integral multiple of blockSize bytes.\r
+         * 4. Use base64 to encode the result of step 3.\r
+         */\r
+        MessageDigest hashMD = getMessageDigest(hashAlgo);\r
+        byte[] hashedVerifier = hashMD.digest(verifier);\r
+        byte encryptedVerifierHash[] = hashInput(builder, pwHash, kHashedVerifierBlock, hashedVerifier, Cipher.ENCRYPT_MODE);\r
+        ver.setEncryptedVerifierHash(encryptedVerifierHash);\r
+        \r
+        /**\r
+         * encryptedKeyValue: This attribute MUST be generated by using the following steps:\r
+         * 1. Generate a random array of bytes that is the same size as specified by the\r
+         *    Encryptor.KeyData.keyBits attribute of the parent element.\r
+         * 2. Generate an encryption key as specified in section 2.3.4.11, using the user-supplied password,\r
+         *    the binary byte array used to create the saltValue attribute, and a blockKey byte array\r
+         *    consisting of the following bytes: 0x14, 0x6e, 0x0b, 0xe7, 0xab, 0xac, 0xd0, and 0xd6.\r
+         * 3. Encrypt the random array of bytes generated in step 1 by using the binary form of the saltValue\r
+         *    attribute as an initialization vector as specified in section 2.3.4.12. If the array of bytes is not an\r
+         *    integral multiple of blockSize bytes, pad the array with 0x00 to an integral multiple of\r
+         *    blockSize bytes.\r
+         * 4. Use base64 to encode the result of step 3.\r
+         */\r
+        byte encryptedKey[] = hashInput(builder, pwHash, kCryptoKeyBlock, keySpec, Cipher.ENCRYPT_MODE);\r
+        ver.setEncryptedKey(encryptedKey);\r
+        \r
+        SecretKey secretKey = new SecretKeySpec(keySpec, ver.getCipherAlgorithm().jceId);\r
+        setSecretKey(secretKey);\r
+        \r
+        /*\r
+         * 2.3.4.14 DataIntegrity Generation (Agile Encryption)\r
+         * \r
+         * The DataIntegrity element contained within an Encryption element MUST be generated by using\r
+         * the following steps:\r
+         * 1. Obtain the intermediate key by decrypting the encryptedKeyValue from a KeyEncryptor\r
+         *    contained within the KeyEncryptors sequence. Use this key for encryption operations in the\r
+         *    remaining steps of this section.\r
+         * 2. Generate a random array of bytes, known as Salt, of the same length as the value of the\r
+         *    KeyData.hashSize attribute.\r
+         * 3. Encrypt the random array of bytes generated in step 2 by using the binary form of the\r
+         *    KeyData.saltValue attribute and a blockKey byte array consisting of the following bytes:\r
+         *    0x5f, 0xb2, 0xad, 0x01, 0x0c, 0xb9, 0xe1, and 0xf6 used to form an initialization vector as\r
+         *    specified in section 2.3.4.12. If the array of bytes is not an integral multiple of blockSize\r
+         *    bytes, pad the array with 0x00 to the next integral multiple of blockSize bytes.\r
+         * 4. Assign the encryptedHmacKey attribute to the base64-encoded form of the result of step 3.\r
+         * 5. Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message),\r
+         *    which the DataIntegrity element will verify by using the Salt generated in step 2 as the key.\r
+         *    Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be\r
+         *    used as the message.\r
+         * 6. Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes:\r
+         *    0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33.\r
+         * 7.  Assign the encryptedHmacValue attribute to the base64-encoded form of the result of step 6. \r
+         */\r
+        this.integritySalt = integritySalt;\r
+\r
+        try {\r
+            byte vec[] = CryptoFunctions.generateIv(hashAlgo, header.getKeySalt(), kIntegrityKeyBlock, header.getBlockSize());\r
+            Cipher cipher = getCipher(secretKey, ver.getCipherAlgorithm(), ver.getChainingMode(), vec, Cipher.ENCRYPT_MODE);\r
+            byte filledSalt[] = getBlock0(integritySalt, getNextBlockSize(integritySalt.length, blockSize));\r
+            byte encryptedHmacKey[] = cipher.doFinal(filledSalt);\r
+            header.setEncryptedHmacKey(encryptedHmacKey);\r
+\r
+            this.integrityMD = CryptoFunctions.getMac(hashAlgo);\r
+            this.integrityMD.init(new SecretKeySpec(integritySalt, hashAlgo.jceHmacId));\r
+\r
+        \r
+            cipher = Cipher.getInstance("RSA");\r
+            for (AgileCertificateEntry ace : ver.getCertificates()) {\r
+                cipher.init(Cipher.ENCRYPT_MODE, ace.x509.getPublicKey());\r
+                ace.encryptedKey = cipher.doFinal(getSecretKey().getEncoded());\r
+                Mac x509Hmac = CryptoFunctions.getMac(hashAlgo);\r
+                x509Hmac.init(getSecretKey());\r
+                ace.certVerifier = x509Hmac.doFinal(ace.x509.getEncoded());\r
+            }\r
+        } catch (GeneralSecurityException e) {\r
+            throw new EncryptedDocumentException(e);\r
+        }\r
+       }\r
+       \r
+    public OutputStream getDataStream(DirectoryNode dir)\r
+            throws IOException, GeneralSecurityException {\r
+        // TODO: initialize headers\r
+        OutputStream countStream = new ChunkedCipherOutputStream(dir);\r
+       return countStream;\r
+    }\r
+\r
+    /**\r
+     * 2.3.4.15 Data Encryption (Agile Encryption)\r
+     * \r
+     * The EncryptedPackage stream (1) MUST be encrypted in 4096-byte segments to facilitate nearly\r
+     * random access while allowing CBC modes to be used in the encryption process.\r
+     * The initialization vector for the encryption process MUST be obtained by using the zero-based\r
+     * segment number as a blockKey and the binary form of the KeyData.saltValue as specified in\r
+     * section 2.3.4.12. The block number MUST be represented as a 32-bit unsigned integer.\r
+     * Data blocks MUST then be encrypted by using the initialization vector and the intermediate key\r
+     * obtained by decrypting the encryptedKeyValue from a KeyEncryptor contained within the\r
+     * KeyEncryptors sequence as specified in section 2.3.4.10. The final data block MUST be padded to\r
+     * the next integral multiple of the KeyData.blockSize value. Any padding bytes can be used. Note\r
+     * that the StreamSize field of the EncryptedPackage field specifies the number of bytes of\r
+     * unencrypted data as specified in section 2.3.4.4.\r
+     */\r
+    private class ChunkedCipherOutputStream extends FilterOutputStream implements POIFSWriterListener {\r
+        private long _pos = 0;\r
+        private final byte[] _chunk = new byte[4096];\r
+        private Cipher _cipher;\r
+        private final File fileOut;\r
+        protected final DirectoryNode dir;\r
+\r
+        public ChunkedCipherOutputStream(DirectoryNode dir) throws IOException {\r
+            super(null);\r
+            fileOut = TempFile.createTempFile("encrypted_package", "crypt");\r
+            this.out = new FileOutputStream(fileOut);\r
+            this.dir = dir;\r
+            EncryptionHeader header = builder.getHeader();\r
+            _cipher = getCipher(getSecretKey(), header.getCipherAlgorithm(), header.getChainingMode(), null, Cipher.ENCRYPT_MODE);\r
+        }\r
+\r
+        public void write(int b) throws IOException {\r
+            write(new byte[]{(byte)b});\r
+        }\r
+\r
+        public void write(byte[] b) throws IOException {\r
+            write(b, 0, b.length);\r
+        }\r
+\r
+        public void write(byte[] b, int off, int len)\r
+        throws IOException {\r
+            if (len == 0) return;\r
+            \r
+            if (len < 0 || b.length < off+len) {\r
+                throw new IOException("not enough bytes in your input buffer");\r
+            }\r
+            \r
+            while (len > 0) {\r
+                int posInChunk = (int)(_pos & 0xfff);\r
+                int nextLen = Math.min(4096-posInChunk, len);\r
+                System.arraycopy(b, off, _chunk, posInChunk, nextLen);\r
+                _pos += nextLen;\r
+                off += nextLen;\r
+                len -= nextLen;\r
+                if ((_pos & 0xfff) == 0) {\r
+                    writeChunk();\r
+                }\r
+            }\r
+        }\r
+\r
+        private void writeChunk() throws IOException {\r
+            EncryptionHeader header = builder.getHeader();\r
+            int blockSize = header.getBlockSize();\r
+\r
+            int posInChunk = (int)(_pos & 0xfff);\r
+            // normally posInChunk is 0, i.e. on the next chunk (-> index-1)\r
+            // but if called on close(), posInChunk is somewhere within the chunk data\r
+            int index = (int)(_pos >> 12);\r
+            if (posInChunk==0) {\r
+                index--;\r
+                posInChunk = 4096;\r
+            } else {\r
+                // pad the last chunk\r
+                _cipher = getCipher(getSecretKey(), header.getCipherAlgorithm(), header.getChainingMode(), null, Cipher.ENCRYPT_MODE, "PKCS5Padding");\r
+            }\r
+\r
+            byte[] blockKey = new byte[4];\r
+            LittleEndian.putInt(blockKey, 0, index);\r
+            byte[] iv = generateIv(header.getHashAlgorithmEx(), header.getKeySalt(), blockKey, blockSize);\r
+            try {\r
+                _cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(), new IvParameterSpec(iv));\r
+                int ciLen = _cipher.doFinal(_chunk, 0, posInChunk, _chunk);\r
+                out.write(_chunk, 0, ciLen);\r
+            } catch (GeneralSecurityException e) {\r
+                throw new IOException(e);\r
+            }\r
+        }\r
+        \r
+        public void close() throws IOException {\r
+            writeChunk();\r
+            super.close();\r
+            writeToPOIFS();\r
+        }\r
+\r
+        void writeToPOIFS() throws IOException {\r
+            DataSpaceMapUtils.addDefaultDataSpace(dir);\r
+            \r
+            /**\r
+             * Generate an HMAC, as specified in [RFC2104], of the encrypted form of the data (message), \r
+             * which the DataIntegrity element will verify by using the Salt generated in step 2 as the key. \r
+             * Note that the entire EncryptedPackage stream (1), including the StreamSize field, MUST be \r
+             * used as the message.\r
+             * \r
+             * Encrypt the HMAC as in step 3 by using a blockKey byte array consisting of the following bytes:\r
+             * 0xa0, 0x67, 0x7f, 0x02, 0xb2, 0x2c, 0x84, and 0x33.\r
+             **/\r
+            byte buf[] = new byte[4096];\r
+            LittleEndian.putLong(buf, 0, _pos);\r
+            integrityMD.update(buf, 0, LittleEndianConsts.LONG_SIZE);\r
+            \r
+            InputStream fis = new FileInputStream(fileOut);\r
+            for (int readBytes; (readBytes = fis.read(buf)) != -1; integrityMD.update(buf, 0, readBytes));\r
+            fis.close();\r
+            \r
+            AgileEncryptionHeader header = builder.getHeader(); \r
+            int blockSize = header.getBlockSize();\r
+            \r
+            byte hmacValue[] = integrityMD.doFinal();\r
+            byte iv[] = CryptoFunctions.generateIv(header.getHashAlgorithmEx(), header.getKeySalt(), kIntegrityValueBlock, header.getBlockSize());\r
+            Cipher cipher = CryptoFunctions.getCipher(getSecretKey(), header.getCipherAlgorithm(), header.getChainingMode(), iv, Cipher.ENCRYPT_MODE);\r
+            try {\r
+                byte hmacValueFilled[] = getBlock0(hmacValue, getNextBlockSize(hmacValue.length, blockSize));\r
+                byte encryptedHmacValue[] = cipher.doFinal(hmacValueFilled);\r
+                header.setEncryptedHmacValue(encryptedHmacValue);\r
+            } catch (GeneralSecurityException e) {\r
+                throw new EncryptedDocumentException(e);\r
+            }\r
+\r
+            createEncryptionInfoEntry(dir);\r
+            \r
+            int oleStreamSize = (int)(fileOut.length()+LittleEndianConsts.LONG_SIZE);\r
+            dir.createDocument("EncryptedPackage", oleStreamSize, this);\r
+            // TODO: any properties???\r
+        }\r
+    \r
+        public void processPOIFSWriterEvent(POIFSWriterEvent event) {\r
+            try {\r
+                LittleEndianOutputStream leos = new LittleEndianOutputStream(event.getStream());\r
+\r
+                // StreamSize (8 bytes): An unsigned integer that specifies the number of bytes used by data \r
+                // encrypted within the EncryptedData field, not including the size of the StreamSize field. \r
+                // Note that the actual size of the \EncryptedPackage stream (1) can be larger than this \r
+                // value, depending on the block size of the chosen encryption algorithm\r
+                leos.writeLong(_pos);\r
+\r
+                FileInputStream fis = new FileInputStream(fileOut);\r
+                IOUtils.copy(fis, leos);\r
+                fis.close();\r
+                fileOut.delete();\r
+\r
+                leos.close();\r
+            } catch (IOException e) {\r
+                throw new EncryptedDocumentException(e);\r
+            }\r
+        }\r
+    }\r
+\r
+    protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {\r
+        AgileEncryptionVerifier ver = builder.getVerifier();\r
+        AgileEncryptionHeader header = builder.getHeader();\r
+        \r
+        EncryptionDocument ed = EncryptionDocument.Factory.newInstance();\r
+        CTEncryption edRoot = ed.addNewEncryption();\r
+        \r
+        CTKeyData keyData = edRoot.addNewKeyData();\r
+        CTKeyEncryptors keyEncList = edRoot.addNewKeyEncryptors();\r
+        CTKeyEncryptor keyEnc = keyEncList.addNewKeyEncryptor();\r
+        keyEnc.setUri(CTKeyEncryptor.Uri.HTTP_SCHEMAS_MICROSOFT_COM_OFFICE_2006_KEY_ENCRYPTOR_PASSWORD);\r
+        CTPasswordKeyEncryptor keyPass = keyEnc.addNewEncryptedPasswordKey();\r
+\r
+        keyPass.setSpinCount(ver.getSpinCount());\r
+        \r
+        keyData.setSaltSize(header.getBlockSize());\r
+        keyPass.setSaltSize(header.getBlockSize());\r
+        \r
+        keyData.setBlockSize(header.getBlockSize());\r
+        keyPass.setBlockSize(header.getBlockSize());\r
+\r
+        keyData.setKeyBits(header.getKeySize());\r
+        keyPass.setKeyBits(header.getKeySize());\r
+\r
+        HashAlgorithm hashAlgo = header.getHashAlgorithmEx();\r
+        keyData.setHashSize(hashAlgo.hashSize);\r
+        keyPass.setHashSize(hashAlgo.hashSize);\r
+\r
+        STCipherAlgorithm.Enum xmlCipherAlgo = STCipherAlgorithm.Enum.forString(header.getCipherAlgorithm().xmlId);\r
+        if (xmlCipherAlgo == null) {\r
+            throw new EncryptedDocumentException("CipherAlgorithm "+header.getCipherAlgorithm()+" not supported.");\r
+        }\r
+        keyData.setCipherAlgorithm(xmlCipherAlgo);\r
+        keyPass.setCipherAlgorithm(xmlCipherAlgo);\r
+        \r
+        switch (header.getChainingMode()) {\r
+        case cbc: \r
+            keyData.setCipherChaining(STCipherChaining.CHAINING_MODE_CBC);\r
+            keyPass.setCipherChaining(STCipherChaining.CHAINING_MODE_CBC);\r
+            break;\r
+        case cfb:\r
+            keyData.setCipherChaining(STCipherChaining.CHAINING_MODE_CFB);\r
+            keyPass.setCipherChaining(STCipherChaining.CHAINING_MODE_CFB);\r
+            break;\r
+        default:\r
+            throw new EncryptedDocumentException("ChainingMode "+header.getChainingMode()+" not supported.");\r
+        }\r
+        \r
+        STHashAlgorithm.Enum xmlHashAlgo = STHashAlgorithm.Enum.forString(hashAlgo.ecmaString);\r
+        if (xmlHashAlgo == null) {\r
+            throw new EncryptedDocumentException("HashAlgorithm "+hashAlgo+" not supported.");\r
+        }\r
+        keyData.setHashAlgorithm(xmlHashAlgo);\r
+        keyPass.setHashAlgorithm(xmlHashAlgo);\r
+\r
+        keyData.setSaltValue(header.getKeySalt());\r
+        keyPass.setSaltValue(ver.getSalt());\r
+        keyPass.setEncryptedVerifierHashInput(ver.getEncryptedVerifier());\r
+        keyPass.setEncryptedVerifierHashValue(ver.getEncryptedVerifierHash());\r
+        keyPass.setEncryptedKeyValue(ver.getEncryptedKey());\r
+        \r
+        CTDataIntegrity hmacData = edRoot.addNewDataIntegrity();\r
+        hmacData.setEncryptedHmacKey(header.getEncryptedHmacKey());\r
+        hmacData.setEncryptedHmacValue(header.getEncryptedHmacValue());\r
+        \r
+        for (AgileCertificateEntry ace : ver.getCertificates()) {\r
+            keyEnc = keyEncList.addNewKeyEncryptor();\r
+            keyEnc.setUri(CTKeyEncryptor.Uri.HTTP_SCHEMAS_MICROSOFT_COM_OFFICE_2006_KEY_ENCRYPTOR_CERTIFICATE);\r
+            CTCertificateKeyEncryptor certData = keyEnc.addNewEncryptedCertificateKey();\r
+            try {\r
+                certData.setX509Certificate(ace.x509.getEncoded());\r
+            } catch (CertificateEncodingException e) {\r
+                throw new EncryptedDocumentException(e);\r
+            }\r
+            certData.setEncryptedKeyValue(ace.encryptedKey);\r
+            certData.setCertVerifier(ace.certVerifier);\r
+        }\r
+\r
+        XmlOptions xo = new XmlOptions();\r
+        xo.setCharacterEncoding("UTF-8");\r
+        Map<String,String> nsMap = new HashMap<String,String>();\r
+        nsMap.put("http://schemas.microsoft.com/office/2006/keyEncryptor/password","p");\r
+        nsMap.put("http://schemas.microsoft.com/office/2006/keyEncryptor/certificate", "c");\r
+        nsMap.put("http://schemas.microsoft.com/office/2006/encryption","");\r
+        xo.setSaveSuggestedPrefixes(nsMap);\r
+        xo.setSaveNamespacesFirst();\r
+        xo.setSaveAggressiveNamespaces();\r
+        // setting standalone doesn't work with xmlbeans-2.3\r
+        xo.setSaveNoXmlDecl();\r
+        \r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
+        bos.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n".getBytes("UTF-8"));\r
+        ed.save(bos, xo);\r
+\r
+        final byte buf[] = new byte[5000];        \r
+        LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0);\r
+        EncryptionInfo info = builder.getInfo();\r
+\r
+        // EncryptionVersionInfo (4 bytes): A Version structure (section 2.1.4), where \r
+        // Version.vMajor MUST be 0x0004 and Version.vMinor MUST be 0x0004\r
+        leos.writeShort(info.getVersionMajor());\r
+        leos.writeShort(info.getVersionMinor());\r
+        // Reserved (4 bytes): A value that MUST be 0x00000040\r
+        leos.writeInt(0x40);\r
+        leos.write(bos.toByteArray());\r
+        \r
+        dir.createDocument("EncryptionInfo", leos.getWriteIndex(), new POIFSWriterListener() {\r
+            public void processPOIFSWriterEvent(POIFSWriterEvent event) {\r
+                try {\r
+                    event.getStream().write(buf, 0, event.getLimit());\r
+                } catch (IOException e) {\r
+                    throw new EncryptedDocumentException(e);\r
+                }\r
+            }\r
+        });\r
+    }\r
+}\r
index cedc906edf7c9d10463ac96cc75b99b3056ea65e..f6d809dc833fd62311df0f1a8c30bfba2fb1426b 100644 (file)
@@ -23,6 +23,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.lang.reflect.Field;
+import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
@@ -32,10 +33,13 @@ import java.util.Vector;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 
+import junit.framework.JUnit4TestAdapter;
 import junit.framework.TestCase;
 import junit.framework.TestSuite;
 import junit.textui.TestRunner;
 
+import org.junit.Test;
+
 /**
  * Build a 'lite' version of the ooxml-schemas.jar
  *
@@ -103,9 +107,18 @@ public final class OOXMLLite {
 
             String cls = arg.replace(".class", "");
             try {
-                @SuppressWarnings("unchecked")
-                               Class<? extends TestCase> test = (Class<? extends TestCase>) Class.forName(cls);
-                suite.addTestSuite(test);
+                Class<?> testclass = Class.forName(cls);
+                boolean isTest = TestCase.class.isAssignableFrom(testclass);
+                if (!isTest) {
+                    for (Method m : testclass.getDeclaredMethods()) {
+                        isTest = m.isAnnotationPresent(Test.class);
+                        if (isTest) break;
+                    }
+                }
+                
+                if (isTest) {
+                    suite.addTest(new JUnit4TestAdapter(testclass));
+                }
             } catch (ClassNotFoundException e) {
                 throw new RuntimeException(e);
             }
@@ -181,8 +194,12 @@ public final class OOXMLLite {
             Vector<Class<?>> classes = (Vector<Class<?>>) _classes.get(appLoader);
             Map<String, Class<?>> map = new HashMap<String, Class<?>>();
             for (Class<?> cls : classes) {
-                String jar = cls.getProtectionDomain().getCodeSource().getLocation().toString();
-                if(jar.indexOf(ptrn) != -1) map.put(cls.getName(), cls);
+                try {
+                    String jar = cls.getProtectionDomain().getCodeSource().getLocation().toString();
+                    if(jar.indexOf(ptrn) != -1) map.put(cls.getName(), cls);
+                } catch (NullPointerException e) {
+                    continue;
+                }
             }
             return map;
         } catch (IllegalAccessException e) {
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsd
new file mode 100644 (file)
index 0000000..7423c85
--- /dev/null
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xs:schema xmlns="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate" xmlns:e="http://schemas.microsoft.com/office/2006/encryption" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate" elementFormDefault="qualified" attributeFormDefault="unqualified">\r
+       <xs:import namespace="http://schemas.microsoft.com/office/2006/encryption" schemaLocation="encryptionInfo.xsd"/>\r
+       <xs:simpleType name="ST_PasswordKeyEncryptorUri">\r
+               <xs:restriction base="xs:token">\r
+                       <xs:enumeration value="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:complexType name="CT_CertificateKeyEncryptor">\r
+               <xs:attribute name="encryptedKeyValue" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies the encrypted form of the intermediate key, which is encrypted with the public key contained within the X509Certificate attribute.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="X509Certificate" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies a DER-encoded X.509 certificate (1) used to encrypt the intermediate key. The certificate (1) MUST contain only the public portion of the public-private key pair.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="certVerifier" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies the HMAC of the binary data obtained by base64-decoding the X509Certificate attribute. The hashing algorithm used to derive the HMAC MUST be the hashing algorithm specified for the Encryption.keyData element. The secret key used to derive the HMAC MUST be the intermediate key. If the intermediate key is reset, any CertificateKeyEncryptor elements are also reset to contain the new intermediate key, except that the certVerifier attribute MUST match the value calculated using the current intermediate key, to verify that the CertificateKeyEncryptor element actually encrypted the current intermediate key. If a CertificateKeyEncryptor element does not have a correct certVerifier attribute, it MUST be discarded.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+       </xs:complexType>\r
+       <xs:element name="encryptedKey" type="CT_CertificateKeyEncryptor"/>\r
+</xs:schema>\r
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionCertificate.xsdconfig
new file mode 100644 (file)
index 0000000..73a27fa
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config" xmlns:c="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate">\r
+\r
+<xb:qname name="c:encryptedKey" javaname="EncryptedCertificateKey"/>\r
+  \r
+</xb:config>
\ No newline at end of file
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsd
new file mode 100644 (file)
index 0000000..5b08560
--- /dev/null
@@ -0,0 +1,259 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xs:schema xmlns="http://schemas.microsoft.com/office/2006/encryption" xmlns:p="http://schemas.microsoft.com/office/2006/keyEncryptor/password" xmlns:c="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://schemas.microsoft.com/office/2006/encryption" elementFormDefault="qualified" attributeFormDefault="unqualified">\r
+       <xs:import namespace="http://schemas.microsoft.com/office/2006/keyEncryptor/password" schemaLocation="encryptionPassword.xsd"/>\r
+       <xs:import namespace="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate" schemaLocation="encryptionCertificate.xsd"/>\r
+       <xs:simpleType name="ST_SaltSize">\r
+               <xs:annotation>\r
+                       <xs:documentation>An unsigned integer that specifies the number of bytes used by a salt. It MUST be at least 1 and no greater than 65,536.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:unsignedInt">\r
+                       <xs:minInclusive value="1"/>\r
+                       <xs:maxInclusive value="65536"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_BlockSize">\r
+               <xs:annotation>\r
+                       <xs:documentation>An unsigned integer that specifies the number of bytes used to encrypt one block of data. It MUST be at least 2, no greater than 4096, and a multiple of 2.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:unsignedInt">\r
+                       <xs:minInclusive value="2"/>\r
+                       <xs:maxInclusive value="4096"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_KeyBits">\r
+               <xs:annotation>\r
+                       <xs:documentation>An unsigned integer that specifies the number of bits used by an encryption algorithm. It MUST be at least 8 and a multiple of 8.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:unsignedInt">\r
+                       <xs:minInclusive value="8"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_HashSize">\r
+               <xs:annotation>\r
+                       <xs:documentation>An unsigned integer that specifies the number of bytes used by a hash value. It MUST be at least 1, no greater than 65,536, and the same number of bytes as the hash algorithm emits.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:unsignedInt">\r
+                       <xs:minInclusive value="1"/>\r
+                       <xs:maxInclusive value="65536"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_SpinCount">\r
+               <xs:annotation>\r
+                       <xs:documentation>An unsigned integer that specifies the number of times to iterate on a hash of a password. It MUST NOT be greater than 10,000,000.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:unsignedInt">\r
+                       <xs:minInclusive value="0"/>\r
+                       <xs:maxInclusive value="10000000"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_CipherAlgorithm">\r
+               <xs:annotation>\r
+                       <xs:appinfo>modified for poi - list is restricted to given list in [ms-offcrypto]</xs:appinfo>\r
+                       <xs:documentation>A string that specifies the cipher algorithm. Values that are not defined MAY be used, and a compliant implementation is not required to support all defined values. Any algorithm that can be resolved by name by the underlying operating system can be used for hashing or encryption. Only block algorithms are supported for encryption. AES-128 is the default encryption algorithm, and SHA-1 is the default hashing algorithm if no other algorithms have been configured.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:token">\r
+                       <xs:enumeration value="AES">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the AES algorithm.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="RC2">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [RFC2268] (http://tools.ietf.org/html/rfc2268). The use of RC2 is not recommended. If RC2 is used with a key length of less than 128 bits, documents could interoperate incorrectly across different versions of Windows.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="RC4">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST NOT be used.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="DES">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the DES algorithm. The use of DES is not recommended. If DES is used, the key length specified in the KeyBits element is required to be set to 64 for 56-bit encryption, and the key decrypted from encryptedKeyValue of KeyEncryptor is required to include the DES parity bits.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="DESX">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [DRAFT-DESX] (http://tools.ietf.org/html/draft-ietf-ipsec-ciph-desx-00). The use of DESX is not recommended. If DESX is used, documents could interoperate incorrectly across different versions of Windows.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="3DES">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [RFC1851] (http://tools.ietf.org/html/rfc1851). If 3DES or 3DES_112 is used, the key length specified in the KeyBits element is required to be set to 192 for 168-bit encryption and 128 for 112-bit encryption, and the key decrypted from encryptedKeyValue of KeyEncryptor is required to include the DES parity bits.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="3DES_112">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see 3DES</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_CipherChaining">\r
+               <xs:annotation>\r
+                       <xs:documentation>A string that specifies the chaining mode used by CipherAlgorithm. For more details about chaining modes, see [BCMO800-38A] (http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf).</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:token">\r
+                       <xs:enumeration value="ChainingModeCBC">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>block chaining (CBC)</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="ChainingModeCFB">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>Cipher feedback chaining (CFB), with an 8-bit window</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:simpleType name="ST_HashAlgorithm">\r
+               <xs:annotation>\r
+                       <xs:appinfo>modified for poi - list is restricted to given list in [ms-offcrypto]</xs:appinfo>\r
+                       <xs:documentation>A string specifying a hashing algorithm. Values that are not defined MAY be used, and a compliant implementation is not required to support all defined values.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:restriction base="xs:token">\r
+                       <xs:enumeration value="SHA1">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [RFC4634] (http://tools.ietf.org/html/rfc4634).</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="SHA256">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see SHA1</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="SHA384">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see SHA1</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="SHA512">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see SHA1</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="MD5">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to MD5.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="MD4">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [RFC1320] (http://tools.ietf.org/html/rfc1320).</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="MD2">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the algorithm as specified in [RFC1319] (http://tools.ietf.org/html/rfc1319).</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="RIPEMD-128">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>MUST conform to the hash functions specified in [ISO/IEC 10118]. (https://en.wikipedia.org/wiki/RIPEMD)</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="RIPEMD-160">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see RIPEMD-128 (https://en.wikipedia.org/wiki/RIPEMD)</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+                       <xs:enumeration value="WHIRLPOOL">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>see RIPEMD-128 (https://en.wikipedia.org/wiki/ISO/IEC_10118-3)</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:enumeration>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:complexType name="CT_KeyData">\r
+               <xs:annotation>\r
+                       <xs:documentation>A complex type that specifies the encryption used within this element. The saltValue attribute is a base64-encoded binary value that is randomly generated. The number of bytes required to decode the saltValue attribute MUST be equal to the value of the saltSize attribute.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:attribute name="saltSize" type="ST_SaltSize" use="required"/>\r
+               <xs:attribute name="blockSize" type="ST_BlockSize" use="required"/>\r
+               <xs:attribute name="keyBits" type="ST_KeyBits" use="required"/>\r
+               <xs:attribute name="hashSize" type="ST_HashSize" use="required"/>\r
+               <xs:attribute name="cipherAlgorithm" type="ST_CipherAlgorithm" use="required"/>\r
+               <xs:attribute name="cipherChaining" type="ST_CipherChaining" use="required"/>\r
+               <xs:attribute name="hashAlgorithm" type="ST_HashAlgorithm" use="required"/>\r
+               <xs:attribute name="saltValue" type="xs:base64Binary" use="required"/>\r
+       </xs:complexType>\r
+       <xs:complexType name="CT_DataIntegrity">\r
+               <xs:annotation>\r
+                       <xs:documentation>A complex type that specifies data used to verify whether the encrypted data passes an integrity check. It MUST be generated using the method specified in section 2.3.4.14 (http://msdn.microsoft.com/en-us/library/dd924068(v=office.12).aspx).</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:attribute name="encryptedHmacKey" type="xs:base64Binary" use="required">\r
+                       <xs:annotation>\r
+                               <xs:documentation>A base64-encoded value that specifies an encrypted key used in calculating the encryptedHmacValue.</xs:documentation>\r
+                       </xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="encryptedHmacValue" type="xs:base64Binary" use="required">\r
+                       <xs:annotation>\r
+                               <xs:documentation>A base64-encoded value that specifies an HMAC derived from encryptedHmacKey and the encrypted data.</xs:documentation>\r
+                       </xs:annotation>\r
+               </xs:attribute>\r
+       </xs:complexType>\r
+       <xs:complexType name="CT_KeyEncryptor">\r
+               <xs:annotation>\r
+                       <xs:appinfo>modified for POI</xs:appinfo>\r
+                       <xs:documentation>A complex type that specifies the parameters used to encrypt an intermediate key, which is used to perform the final encryption of the document. To ensure extensibility, arbitrary elements can be defined to encrypt the intermediate key. The intermediate key MUST be the same for all KeyEncryptor elements.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:choice>\r
+                       <xs:element ref="p:encryptedKey"/>\r
+                       <xs:element ref="c:encryptedKey"/>\r
+               </xs:choice>\r
+               <xs:attribute name="uri">\r
+                       <xs:annotation>\r
+                               <xs:appinfo>modified for POI</xs:appinfo>\r
+                       </xs:annotation>\r
+                       <xs:simpleType>\r
+                               <xs:restriction base="xs:token">\r
+                                       <xs:enumeration value="http://schemas.microsoft.com/office/2006/keyEncryptor/password"/>\r
+                                       <xs:enumeration value="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate"/>\r
+                               </xs:restriction>\r
+                       </xs:simpleType>\r
+               </xs:attribute>\r
+       </xs:complexType>\r
+       <xs:complexType name="CT_KeyEncryptors">\r
+               <xs:annotation>\r
+                       <xs:documentation>A sequence of KeyEncryptor elements. Exactly one KeyEncryptors element MUST be present, and the KeyEncryptors element MUST contain at least one KeyEncryptor.</xs:documentation>\r
+               </xs:annotation>\r
+               <xs:sequence>\r
+                       <xs:element name="keyEncryptor" type="CT_KeyEncryptor" maxOccurs="unbounded"/>\r
+               </xs:sequence>\r
+       </xs:complexType>\r
+       <xs:complexType name="CT_Encryption">\r
+               <xs:sequence>\r
+                       <xs:element name="keyData" type="CT_KeyData"/>\r
+                       <xs:element name="dataIntegrity" type="CT_DataIntegrity">\r
+                               <xs:annotation>\r
+                                       <xs:appinfo>modified for POI</xs:appinfo>\r
+                                       <xs:documentation>All ECMA-376 documents [ECMA-376] encrypted by Microsoft Office using agile encryption will have a DataIntegrity element present. The schema allows for a DataIntegrity element to not be present because the encryption schema can be used by applications that do not create ECMA-376 documents [ECMA-376].</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:element>\r
+                       <xs:element name="keyEncryptors" type="CT_KeyEncryptors">\r
+                               <xs:annotation>\r
+                                       <xs:documentation>The KeyEncryptor element, which MUST be used when encrypting password-protected agile encryption documents, is either a PasswordKeyEncryptor or a CertificateKeyEncryptor. Exactly one PasswordKeyEncryptor MUST be present. Zero or more CertificateKeyEncryptor elements are contained within the KeyEncryptors element.</xs:documentation>\r
+                               </xs:annotation>\r
+                       </xs:element>\r
+               </xs:sequence>\r
+       </xs:complexType>\r
+       <xs:element name="encryption" type="CT_Encryption"/>\r
+</xs:schema>\r
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionInfo.xsdconfig
new file mode 100644 (file)
index 0000000..c9474a0
--- /dev/null
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config" xmlns:c="http://schemas.microsoft.com/office/2006/keyEncryptor/certificate" xmlns:p="http://schemas.microsoft.com/office/2006/keyEncryptor/password">\r
+\r
+<xb:qname name="c:encryptedKey" javaname="EncryptedCertificateKey"/>\r
+<xb:qname name="p:encryptedKey" javaname="EncryptedPasswordKey"/>\r
+  \r
+</xb:config>
\ No newline at end of file
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsd
new file mode 100644 (file)
index 0000000..79ae888
--- /dev/null
@@ -0,0 +1,66 @@
+<?xml version="1.0" encoding="utf-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xs:schema xmlns="http://schemas.microsoft.com/office/2006/keyEncryptor/password" xmlns:e="http://schemas.microsoft.com/office/2006/encryption" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://schemas.microsoft.com/office/2006/keyEncryptor/password" elementFormDefault="qualified" attributeFormDefault="unqualified">\r
+       <xs:import namespace="http://schemas.microsoft.com/office/2006/encryption" schemaLocation="encryptionInfo.xsd"/>\r
+       <xs:simpleType name="ST_PasswordKeyEncryptorUri">\r
+               <xs:restriction base="xs:token">\r
+                       <xs:enumeration value="http://schemas.microsoft.com/office/2006/keyEncryptor/password"/>\r
+               </xs:restriction>\r
+       </xs:simpleType>\r
+       <xs:complexType name="CT_PasswordKeyEncryptor">\r
+               <xs:attribute name="saltSize" type="e:ST_SaltSize" use="required">\r
+                       <xs:annotation><xs:documentation>A SaltSize that specifies the size of the salt for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="blockSize" type="e:ST_BlockSize" use="required">\r
+                       <xs:annotation><xs:documentation>A BlockSize that specifies the block size for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="keyBits" type="e:ST_KeyBits" use="required">\r
+                       <xs:annotation><xs:documentation>A KeyBits that specifies the number of bits for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="hashSize" type="e:ST_HashSize" use="required">\r
+                       <xs:annotation><xs:documentation>A HashSize that specifies the size of the binary form of the hash for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="cipherAlgorithm" type="e:ST_CipherAlgorithm" use="required">\r
+                       <xs:annotation><xs:documentation>A CipherAlgorithm that specifies the cipher algorithm for a PasswordKeyEncryptor. The cipher algorithm specified MUST be the same as the cipher algorithm specified for the Encryption.keyData element.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="cipherChaining" type="e:ST_CipherChaining" use="required">\r
+                       <xs:annotation><xs:documentation>A CipherChaining that specifies the cipher chaining mode for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="hashAlgorithm" type="e:ST_HashAlgorithm" use="required">\r
+                       <xs:annotation><xs:documentation>A HashAlgorithm that specifies the hashing algorithm for a PasswordKeyEncryptor. The hashing algorithm specified MUST be the same as the hashing algorithm specified for the Encryption.keyData element.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="saltValue" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded binary byte array that specifies the salt value for a PasswordKeyEncryptor. The number of bytes required by the decoded form of this element MUST be saltSize.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="spinCount" type="e:ST_SpinCount" use="required">\r
+                       <xs:annotation><xs:documentation>A SpinCount that specifies the spin count for a PasswordKeyEncryptor.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="encryptedVerifierHashInput" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies the encrypted verifier hash input for a PasswordKeyEncryptor used in password verification.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="encryptedVerifierHashValue" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies the encrypted verifier hash value for a PasswordKeyEncryptor used in password verification.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+               <xs:attribute name="encryptedKeyValue" type="xs:base64Binary" use="required">\r
+                       <xs:annotation><xs:documentation>A base64-encoded value that specifies the encrypted form of the intermediate key.</xs:documentation></xs:annotation>\r
+               </xs:attribute>\r
+       </xs:complexType>\r
+       <xs:element name="encryptedKey" type="CT_PasswordKeyEncryptor"/>\r
+</xs:schema>\r
diff --git a/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig b/src/ooxml/resources/org/apache/poi/poifs/crypt/encryptionPassword.xsdconfig
new file mode 100644 (file)
index 0000000..3a2bb2c
--- /dev/null
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>\r
+<!--\r
+   ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+   ====================================================================\r
+-->\r
+<xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config" xmlns:p="http://schemas.microsoft.com/office/2006/keyEncryptor/password">\r
+\r
+<xb:qname name="p:encryptedKey" javaname="EncryptedPasswordKey"/>\r
+  \r
+</xb:config>
\ No newline at end of file
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java
new file mode 100644 (file)
index 0000000..fd8e56a
--- /dev/null
@@ -0,0 +1,36 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import org.junit.runner.RunWith;\r
+import org.junit.runners.Suite;\r
+\r
+\r
+/**\r
+ * Tests for org.apache.poi.poifs.crypt\r
+ */\r
+@RunWith(Suite.class)\r
+@Suite.SuiteClasses({\r
+      TestEncryptionInfo.class\r
+    , TestDecryptor.class\r
+    , TestEncryptor.class\r
+    , TestAgileEncryptionParameters.class\r
+    , TestCertificateEncryption.class\r
+})\r
+public final class AllPOIFSCryptoTests {\r
+}
\ No newline at end of file
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestAgileEncryptionParameters.java
new file mode 100644 (file)
index 0000000..4692866
--- /dev/null
@@ -0,0 +1,102 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import static org.hamcrest.core.IsEqual.equalTo;\r
+import static org.junit.Assert.assertThat;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.util.ArrayList;\r
+import java.util.Collection;\r
+import java.util.List;\r
+\r
+import org.apache.poi.POIDataSamples;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+import org.apache.poi.util.IOUtils;\r
+import org.junit.BeforeClass;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.junit.runners.Parameterized;\r
+import org.junit.runners.Parameterized.Parameter;\r
+import org.junit.runners.Parameterized.Parameters;\r
+\r
+@RunWith(Parameterized.class)\r
+public class TestAgileEncryptionParameters {\r
+\r
+    static byte testData[];\r
+    \r
+    @Parameter(value = 0)\r
+    public CipherAlgorithm ca;\r
+    @Parameter(value = 1)\r
+    public HashAlgorithm ha;\r
+    @Parameter(value = 2)\r
+    public ChainingMode cm;\r
+\r
+    @Parameters\r
+    public static Collection<Object[]> data() {\r
+        CipherAlgorithm caList[] = { CipherAlgorithm.aes128, CipherAlgorithm.aes192, CipherAlgorithm.aes256, CipherAlgorithm.rc2, CipherAlgorithm.des, CipherAlgorithm.des3 };\r
+        HashAlgorithm haList[] = { HashAlgorithm.sha1, HashAlgorithm.sha256, HashAlgorithm.sha384, HashAlgorithm.sha512, HashAlgorithm.md5 };\r
+        ChainingMode cmList[] = { ChainingMode.cbc, ChainingMode.cfb };\r
+\r
+        List<Object[]> data = new ArrayList<Object[]>();\r
+        for (CipherAlgorithm ca : caList) {\r
+            for (HashAlgorithm ha : haList) {\r
+                for (ChainingMode cm : cmList) {\r
+                    data.add(new Object[]{ca,ha,cm});\r
+                }\r
+            }\r
+        }\r
+        \r
+        return data;\r
+    }\r
+    \r
+    @BeforeClass\r
+    public static void initTestData() throws Exception {\r
+        InputStream testFile = POIDataSamples.getDocumentInstance().openResourceAsStream("SampleDoc.docx");\r
+        testData = IOUtils.toByteArray(testFile);\r
+        testFile.close();\r
+    }\r
+    \r
+    @Test\r
+    public void testAgileEncryptionModes() throws Exception {\r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
+\r
+        POIFSFileSystem fsEnc = new POIFSFileSystem();\r
+        EncryptionInfo infoEnc = new EncryptionInfo(fsEnc, EncryptionMode.agile, ca, ha, -1, -1, cm);\r
+        Encryptor enc = infoEnc.getEncryptor();\r
+        enc.confirmPassword("foobaa");\r
+        OutputStream os = enc.getDataStream(fsEnc);\r
+        os.write(testData);\r
+        os.close();\r
+        bos.reset();\r
+        fsEnc.writeFilesystem(bos);\r
+        \r
+        POIFSFileSystem fsDec = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));\r
+        EncryptionInfo infoDec = new EncryptionInfo(fsDec);\r
+        Decryptor dec = infoDec.getDecryptor();\r
+        boolean passed = dec.verifyPassword("foobaa");\r
+        assertTrue(passed);\r
+        InputStream is = dec.getDataStream(fsDec);\r
+        byte actualData[] = IOUtils.toByteArray(is);\r
+        is.close();\r
+        assertThat("Failed roundtrip - "+ca+"-"+ha+"-"+cm, testData, equalTo(actualData));\r
+    }\r
+}\r
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestCertificateEncryption.java
new file mode 100644 (file)
index 0000000..d74719c
--- /dev/null
@@ -0,0 +1,193 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import static org.hamcrest.core.IsEqual.equalTo;\r
+import static org.junit.Assert.assertThat;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.math.BigInteger;\r
+import java.security.GeneralSecurityException;\r
+import java.security.KeyPair;\r
+import java.security.KeyPairGenerator;\r
+import java.security.KeyStore;\r
+import java.security.PrivateKey;\r
+import java.security.PublicKey;\r
+import java.security.SecureRandom;\r
+import java.security.cert.Certificate;\r
+import java.security.cert.X509Certificate;\r
+import java.util.Date;\r
+\r
+import org.apache.poi.POIDataSamples;\r
+import org.apache.poi.poifs.crypt.agile.AgileDecryptor;\r
+import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+import org.apache.poi.util.IOUtils;\r
+import org.junit.BeforeClass;\r
+import org.junit.Test;\r
+\r
+import sun.security.x509.AlgorithmId;\r
+import sun.security.x509.CertificateAlgorithmId;\r
+import sun.security.x509.CertificateIssuerName;\r
+import sun.security.x509.CertificateSerialNumber;\r
+import sun.security.x509.CertificateSubjectName;\r
+import sun.security.x509.CertificateValidity;\r
+import sun.security.x509.CertificateVersion;\r
+import sun.security.x509.CertificateX509Key;\r
+import sun.security.x509.X500Name;\r
+import sun.security.x509.X509CertImpl;\r
+import sun.security.x509.X509CertInfo;\r
+\r
+/**\r
+ * {@linkplain http://stackoverflow.com/questions/1615871/creating-an-x509-certificate-in-java-without-bouncycastle}\r
+ */\r
+public class TestCertificateEncryption {\r
+    /**\r
+     * how many days from now the Certificate is valid for\r
+     */\r
+    static final int days = 1000;\r
+    /**\r
+     * the signing algorithm, eg "SHA1withRSA"\r
+     */\r
+    static final String algorithm = "SHA1withRSA";\r
+    static final String password = "foobaa";\r
+    static final String certAlias = "poitest";\r
+    /**\r
+     * the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"\r
+     */\r
+    static final String certDN = "CN=poitest";\r
+    // static final File pfxFile = TempFile.createTempFile("poitest", ".pfx");\r
+    static byte pfxFileBytes[];\r
+    \r
+    static class CertData {\r
+        KeyPair keypair;\r
+        X509Certificate x509;\r
+    }\r
+    \r
+    /** \r
+     * Create a self-signed X.509 Certificate\r
+     * \r
+     * The keystore generation / loading is split, because normally the keystore would\r
+     * already exist.\r
+     */ \r
+    @BeforeClass\r
+    public static void initKeystore() throws GeneralSecurityException, IOException {\r
+        CertData certData = new CertData();\r
+        \r
+        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");\r
+        keyGen.initialize(1024);\r
+        certData.keypair = keyGen.generateKeyPair();\r
+        PrivateKey privkey = certData.keypair.getPrivate();\r
+        PublicKey publkey = certData.keypair.getPublic();\r
+    \r
+        X509CertInfo info = new X509CertInfo();\r
+        Date from = new Date();\r
+        Date to = new Date(from.getTime() + days * 86400000l);\r
+        CertificateValidity interval = new CertificateValidity(from, to);\r
+        BigInteger sn = new BigInteger(64, new SecureRandom());\r
+        X500Name owner = new X500Name(certDN);\r
+        \r
+        info.set(X509CertInfo.VALIDITY, interval);\r
+        info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));\r
+        info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));\r
+        info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));\r
+        info.set(X509CertInfo.KEY, new CertificateX509Key(publkey));\r
+        info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));\r
+        AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);\r
+        info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));\r
+        \r
+        // Sign the cert to identify the algorithm that's used.\r
+        X509CertImpl cert = new X509CertImpl(info);\r
+        cert.sign(privkey, algorithm);\r
+        \r
+        // Update the algorith, and resign.\r
+        algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);\r
+        info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);\r
+        cert = new X509CertImpl(info);\r
+        cert.sign(privkey, algorithm);\r
+        certData.x509 = cert;\r
+        \r
+        KeyStore keystore = KeyStore.getInstance("PKCS12");\r
+        keystore.load(null, password.toCharArray());\r
+        keystore.setKeyEntry(certAlias, certData.keypair.getPrivate(), password.toCharArray(), new Certificate[]{certData.x509});\r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
+        keystore.store(bos, password.toCharArray());\r
+        pfxFileBytes = bos.toByteArray();\r
+    }\r
+\r
+    public CertData loadKeystore()\r
+    throws GeneralSecurityException, IOException {\r
+        KeyStore keystore = KeyStore.getInstance("PKCS12");\r
+        \r
+        InputStream fis = new ByteArrayInputStream(pfxFileBytes);\r
+        keystore.load(fis, password.toCharArray());\r
+        \r
+        X509Certificate x509 = (X509Certificate)keystore.getCertificate(certAlias);\r
+        PrivateKey privateKey = (PrivateKey)keystore.getKey(certAlias, password.toCharArray());\r
+        PublicKey publicKey = x509.getPublicKey();\r
+\r
+        CertData certData = new CertData();\r
+        certData.keypair = new KeyPair(publicKey, privateKey);\r
+        certData.x509 = x509;\r
+        \r
+        return certData;\r
+    }\r
+    \r
+    @Test\r
+    public void testCertificateEncryption() throws Exception {\r
+        POIFSFileSystem fs = new POIFSFileSystem();\r
+        EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha1, -1, -1, ChainingMode.cbc);\r
+        AgileEncryptionVerifier aev = (AgileEncryptionVerifier)info.getVerifier();\r
+        CertData certData = loadKeystore();\r
+        aev.addCertificate(certData.x509);\r
+        \r
+        Encryptor enc = info.getEncryptor();\r
+        enc.confirmPassword("foobaa");\r
+        \r
+        File file = POIDataSamples.getDocumentInstance().getFile("VariousPictures.docx");\r
+        InputStream fis = new FileInputStream(file);\r
+        byte byteExpected[] = IOUtils.toByteArray(fis);\r
+        fis.close();\r
+        \r
+        OutputStream os = enc.getDataStream(fs);\r
+        IOUtils.copy(new ByteArrayInputStream(byteExpected), os);\r
+        os.close();\r
+        \r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
+        fs.writeFilesystem(bos);\r
+        bos.close();\r
+        \r
+        fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));\r
+        info = new EncryptionInfo(fs);\r
+        AgileDecryptor agDec = (AgileDecryptor)info.getDecryptor();\r
+        boolean passed = agDec.verifyPassword(certData.keypair, certData.x509);\r
+        assertTrue("certificate verification failed", passed);\r
+        \r
+        fis = agDec.getDataStream(fs);\r
+        byte byteActual[] = IOUtils.toByteArray(fis);\r
+        fis.close();\r
+        \r
+        assertThat(byteExpected, equalTo(byteActual));\r
+    }\r
+}\r
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java
new file mode 100644 (file)
index 0000000..95a94c4
--- /dev/null
@@ -0,0 +1,118 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.security.GeneralSecurityException;\r
+import java.util.zip.ZipEntry;\r
+import java.util.zip.ZipInputStream;\r
+\r
+import junit.framework.TestCase;\r
+\r
+import org.apache.poi.POIDataSamples;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+\r
+/**\r
+ *  @author Maxim Valyanskiy\r
+ *  @author Gary King\r
+ */\r
+public class TestDecryptor extends TestCase {\r
+    public void testPasswordVerification() throws IOException, GeneralSecurityException {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        Decryptor d = Decryptor.getInstance(info);\r
+\r
+        assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD));\r
+    }\r
+\r
+    public void testDecrypt() throws IOException, GeneralSecurityException {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        Decryptor d = Decryptor.getInstance(info);\r
+\r
+        d.verifyPassword(Decryptor.DEFAULT_PASSWORD);\r
+\r
+        zipOk(fs, d);\r
+    }\r
+\r
+    public void testAgile() throws IOException, GeneralSecurityException {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        assertTrue(info.getVersionMajor() == 4 && info.getVersionMinor() == 4);\r
+\r
+        Decryptor d = Decryptor.getInstance(info);\r
+\r
+        assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD));\r
+\r
+        zipOk(fs, d);\r
+    }\r
+\r
+    private void zipOk(POIFSFileSystem fs, Decryptor d) throws IOException, GeneralSecurityException {\r
+        ZipInputStream zin = new ZipInputStream(d.getDataStream(fs));\r
+\r
+        while (true) {\r
+            ZipEntry entry = zin.getNextEntry();\r
+            if (entry==null) {\r
+                break;\r
+            }\r
+\r
+            while (zin.available()>0) {\r
+                zin.skip(zin.available());\r
+            }\r
+        }\r
+    }\r
+    public void testDataLength() throws Exception {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        Decryptor d = Decryptor.getInstance(info);\r
+\r
+        d.verifyPassword(Decryptor.DEFAULT_PASSWORD);\r
+\r
+        InputStream is = d.getDataStream(fs);\r
+\r
+        long len = d.getLength();\r
+        assertEquals(12810, len);\r
+\r
+        byte[] buf = new byte[(int)len];\r
+\r
+        is.read(buf);\r
+\r
+        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(buf));\r
+\r
+        while (true) {\r
+            ZipEntry entry = zin.getNextEntry();\r
+            if (entry==null) {\r
+                break;\r
+            }\r
+\r
+            while (zin.available()>0) {\r
+                zin.skip(zin.available());\r
+            }\r
+        }\r
+    }\r
+\r
+}
\ No newline at end of file
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java
new file mode 100644 (file)
index 0000000..698adb8
--- /dev/null
@@ -0,0 +1,61 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+\r
+import java.io.IOException;\r
+\r
+import org.apache.poi.POIDataSamples;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+import org.junit.Test;\r
+\r
+public class TestEncryptionInfo {\r
+    @Test\r
+    public void testEncryptionInfo() throws IOException {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        assertEquals(3, info.getVersionMajor());\r
+        assertEquals(2, info.getVersionMinor());\r
+\r
+        assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm());\r
+        assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());\r
+        assertEquals(128, info.getHeader().getKeySize());\r
+        assertEquals(32, info.getVerifier().getEncryptedVerifierHash().length);\r
+        assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider());                \r
+        assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName());\r
+    }\r
+    \r
+    @Test\r
+    public void testEncryptionInfoSHA512() throws Exception {\r
+        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_sha512.xlsx"));\r
+\r
+        EncryptionInfo info = new EncryptionInfo(fs);\r
+\r
+        assertEquals(4, info.getVersionMajor());\r
+        assertEquals(4, info.getVersionMinor());\r
+\r
+        assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm());\r
+        assertEquals(HashAlgorithm.sha512, info.getHeader().getHashAlgorithmEx());\r
+        assertEquals(256, info.getHeader().getKeySize());\r
+        assertEquals(64, info.getVerifier().getEncryptedVerifierHash().length);\r
+        assertEquals(CipherProvider.aes, info.getHeader().getCipherProvider());                \r
+//        assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName());\r
+    }\r
+}\r
diff --git a/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java b/src/ooxml/testcases/org/apache/poi/poifs/crypt/TestEncryptor.java
new file mode 100644 (file)
index 0000000..957ec10
--- /dev/null
@@ -0,0 +1,253 @@
+/* ====================================================================\r
+   Licensed to the Apache Software Foundation (ASF) under one or more\r
+   contributor license agreements.  See the NOTICE file distributed with\r
+   this work for additional information regarding copyright ownership.\r
+   The ASF licenses this file to You under the Apache License, Version 2.0\r
+   (the "License"); you may not use this file except in compliance with\r
+   the License.  You may obtain a copy of the License at\r
+\r
+       http://www.apache.org/licenses/LICENSE-2.0\r
+\r
+   Unless required by applicable law or agreed to in writing, software\r
+   distributed under the License is distributed on an "AS IS" BASIS,\r
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+   See the License for the specific language governing permissions and\r
+   limitations under the License.\r
+==================================================================== */\r
+package org.apache.poi.poifs.crypt;\r
+\r
+import static org.hamcrest.core.IsEqual.equalTo;\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertThat;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import java.io.ByteArrayInputStream;\r
+import java.io.ByteArrayOutputStream;\r
+import java.io.File;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStream;\r
+import java.io.OutputStream;\r
+import java.util.Iterator;\r
+\r
+import org.apache.poi.POIDataSamples;\r
+import org.apache.poi.poifs.crypt.agile.AgileEncryptionHeader;\r
+import org.apache.poi.poifs.filesystem.DirectoryNode;\r
+import org.apache.poi.poifs.filesystem.DocumentNode;\r
+import org.apache.poi.poifs.filesystem.Entry;\r
+import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;\r
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;\r
+import org.apache.poi.util.BoundedInputStream;\r
+import org.apache.poi.util.IOUtils;\r
+import org.junit.Test;\r
+\r
+public class TestEncryptor {\r
+    @Test\r
+    public void testAgileEncryption() throws Exception {\r
+        File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-pass.docx");\r
+        String pass = "pass";\r
+        NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);\r
+\r
+        // Check the encryption details\r
+        EncryptionInfo infoExpected = new EncryptionInfo(nfs);\r
+        Decryptor decExpected = Decryptor.getInstance(infoExpected);\r
+        boolean passed = decExpected.verifyPassword(pass);\r
+        assertTrue("Unable to process: document is encrypted", passed);\r
+        \r
+        // extract the payload\r
+        InputStream is = decExpected.getDataStream(nfs);\r
+        byte payloadExpected[] = IOUtils.toByteArray(is);\r
+        is.close();\r
+\r
+        long decPackLenExpected = decExpected.getLength();\r
+        assertEquals(decPackLenExpected, payloadExpected.length);\r
+\r
+        is = nfs.getRoot().createDocumentInputStream("EncryptedPackage");\r
+        is = new BoundedInputStream(is, is.available()-16); // ignore padding block\r
+        byte encPackExpected[] = IOUtils.toByteArray(is);\r
+        is.close();\r
+        \r
+        // listDir(nfs.getRoot(), "orig", "");\r
+        \r
+        nfs.close();\r
+\r
+        // check that same verifier/salt lead to same hashes\r
+        byte verifierSaltExpected[] = infoExpected.getVerifier().getSalt();\r
+        byte verifierExpected[] = decExpected.getVerifier();\r
+        byte keySalt[] = infoExpected.getHeader().getKeySalt();\r
+        byte keySpec[] = decExpected.getSecretKey().getEncoded();\r
+        byte integritySalt[] = decExpected.getIntegrityHmacKey();\r
+        // the hmacs of the file always differ, as we use PKCS5-padding to pad the bytes\r
+        // whereas office just uses random bytes\r
+        // byte integrityHash[] = d.getIntegrityHmacValue();\r
+        \r
+        POIFSFileSystem fs = new POIFSFileSystem();\r
+        EncryptionInfo infoActual = new EncryptionInfo(\r
+              fs, EncryptionMode.agile\r
+            , infoExpected.getVerifier().getCipherAlgorithm()\r
+            , infoExpected.getVerifier().getHashAlgorithm()\r
+            , infoExpected.getHeader().getKeySize()\r
+            , infoExpected.getHeader().getBlockSize()\r
+            , infoExpected.getVerifier().getChainingMode()\r
+        );        \r
+\r
+        Encryptor e = Encryptor.getInstance(infoActual);\r
+        e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);\r
+    \r
+        OutputStream os = e.getDataStream(fs);\r
+        IOUtils.copy(new ByteArrayInputStream(payloadExpected), os);\r
+        os.close();\r
+\r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream(); \r
+        fs.writeFilesystem(bos);\r
+        \r
+        nfs = new NPOIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));\r
+        infoActual = new EncryptionInfo(nfs.getRoot());\r
+        Decryptor decActual = Decryptor.getInstance(infoActual);\r
+        passed = decActual.verifyPassword(pass);        \r
+        assertTrue("Unable to process: document is encrypted", passed);\r
+        \r
+        // extract the payload\r
+        is = decActual.getDataStream(nfs);\r
+        byte payloadActual[] = IOUtils.toByteArray(is);\r
+        is.close();\r
+        \r
+        long decPackLenActual = decActual.getLength();\r
+        \r
+        is = nfs.getRoot().createDocumentInputStream("EncryptedPackage");\r
+        is = new BoundedInputStream(is, is.available()-16); // ignore padding block\r
+        byte encPackActual[] = IOUtils.toByteArray(is);\r
+        is.close();\r
+        \r
+        // listDir(nfs.getRoot(), "copy", "");\r
+        \r
+        nfs.close();\r
+        \r
+        AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.getHeader();\r
+        AgileEncryptionHeader aehActual = (AgileEncryptionHeader)infoActual.getHeader();\r
+        assertThat(aehExpected.getEncryptedHmacKey(), equalTo(aehActual.getEncryptedHmacKey()));\r
+        assertEquals(decPackLenExpected, decPackLenActual);\r
+        assertThat(payloadExpected, equalTo(payloadActual));\r
+        assertThat(encPackExpected, equalTo(encPackActual));\r
+    }\r
+    \r
+    @Test\r
+    public void testStandardEncryption() throws Exception {\r
+        File file = POIDataSamples.getDocumentInstance().getFile("bug53475-password-is-solrcell.docx");\r
+        String pass = "solrcell";\r
+        \r
+        NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);\r
+\r
+        // Check the encryption details\r
+        EncryptionInfo infoExpected = new EncryptionInfo(nfs);\r
+        Decryptor d = Decryptor.getInstance(infoExpected);\r
+        boolean passed = d.verifyPassword(pass);\r
+        assertTrue("Unable to process: document is encrypted", passed);\r
+\r
+        // extract the payload\r
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
+        InputStream is = d.getDataStream(nfs);\r
+        IOUtils.copy(is, bos);\r
+        is.close();\r
+        nfs.close();\r
+        byte payloadExpected[] = bos.toByteArray();\r
+        \r
+        // check that same verifier/salt lead to same hashes\r
+        byte verifierSaltExpected[] = infoExpected.getVerifier().getSalt();\r
+        byte verifierExpected[] = d.getVerifier();\r
+        byte keySpec[] = d.getSecretKey().getEncoded();\r
+        byte keySalt[] = infoExpected.getHeader().getKeySalt();\r
+        \r
+        \r
+        POIFSFileSystem fs = new POIFSFileSystem();\r
+        EncryptionInfo infoActual = new EncryptionInfo(\r
+              fs, EncryptionMode.standard\r
+            , infoExpected.getVerifier().getCipherAlgorithm()\r
+            , infoExpected.getVerifier().getHashAlgorithm()\r
+            , infoExpected.getHeader().getKeySize()\r
+            , infoExpected.getHeader().getBlockSize()\r
+            , infoExpected.getVerifier().getChainingMode()\r
+        );\r
+        \r
+        Encryptor e = Encryptor.getInstance(infoActual);\r
+        e.confirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);\r
+        \r
+        assertThat(infoExpected.getVerifier().getEncryptedVerifier(), equalTo(infoActual.getVerifier().getEncryptedVerifier()));\r
+        assertThat(infoExpected.getVerifier().getEncryptedVerifierHash(), equalTo(infoActual.getVerifier().getEncryptedVerifierHash()));\r
+\r
+        // now we use a newly generated salt/verifier and check\r
+        // if the file content is still the same \r
+\r
+        fs = new POIFSFileSystem();\r
+        infoActual = new EncryptionInfo(\r
+              fs, EncryptionMode.standard\r
+            , infoExpected.getVerifier().getCipherAlgorithm()\r
+            , infoExpected.getVerifier().getHashAlgorithm()\r
+            , infoExpected.getHeader().getKeySize()\r
+            , infoExpected.getHeader().getBlockSize()\r
+            , infoExpected.getVerifier().getChainingMode()\r
+        );\r
+        \r
+        e = Encryptor.getInstance(infoActual);\r
+        e.confirmPassword(pass);\r
+        \r
+        OutputStream os = e.getDataStream(fs);\r
+        IOUtils.copy(new ByteArrayInputStream(payloadExpected), os);\r
+        os.close();\r
+        \r
+        bos.reset();\r
+        fs.writeFilesystem(bos);\r
+\r
+        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());\r
+        \r
+        // FileOutputStream fos = new FileOutputStream("encrypted.docx");\r
+        // IOUtils.copy(bis, fos);\r
+        // fos.close();\r
+        // bis.reset();\r
+        \r
+        nfs = new NPOIFSFileSystem(bis);\r
+        infoExpected = new EncryptionInfo(nfs);\r
+        d = Decryptor.getInstance(infoExpected);\r
+        passed = d.verifyPassword(pass);\r
+        assertTrue("Unable to process: document is encrypted", passed);\r
+\r
+        bos.reset();\r
+        is = d.getDataStream(nfs);\r
+        IOUtils.copy(is, bos);\r
+        is.close();\r
+        nfs.close();\r
+        byte payloadActual[] = bos.toByteArray();        \r
+        \r
+        assertThat(payloadExpected, equalTo(payloadActual));\r
+    }\r
+    \r
+    \r
+    private void listEntry(DocumentNode de, String ext, String path) throws IOException {\r
+        path += "\\" + de.getName().replace('\u0006', '_');\r
+        System.out.println(ext+": "+path+" ("+de.getSize()+" bytes)");\r
+        \r
+        String name = de.getName().replace('\u0006', '_');\r
+        \r
+        InputStream is = ((DirectoryNode)de.getParent()).createDocumentInputStream(de);\r
+        FileOutputStream fos = new FileOutputStream("solr."+name+"."+ext);\r
+        IOUtils.copy(is, fos);\r
+        fos.close();\r
+        is.close();\r
+    }\r
+    \r
+    @SuppressWarnings("unused")\r
+    private void listDir(DirectoryNode dn, String ext, String path) throws IOException {\r
+        path += "\\" + dn.getName().replace('\u0006', '_');\r
+        System.out.println(ext+": "+path+" ("+dn.getStorageClsid()+")");\r
+        \r
+        Iterator<Entry> iter = dn.getEntries();\r
+        while (iter.hasNext()) {\r
+            Entry ent = iter.next();\r
+            if (ent instanceof DirectoryNode) {\r
+                listDir((DirectoryNode)ent, ext, path);\r
+            } else {\r
+                listEntry((DocumentNode)ent, ext, path);\r
+            }\r
+        }\r
+    }\r
+}\r
index a0a97cd1166e482fdceb0a4f858db122fdd062f7..f0ddad5ba7f644c7e9eeda276d3ca6b904a1b376 100644 (file)
@@ -11,9 +11,10 @@ import javax.crypto.Cipher;
 \r
 import org.apache.poi.POIDataSamples;\r
 import org.apache.poi.openxml4j.opc.OPCPackage;\r
+import org.apache.poi.poifs.crypt.CipherAlgorithm;\r
 import org.apache.poi.poifs.crypt.Decryptor;\r
-import org.apache.poi.poifs.crypt.EncryptionHeader;\r
 import org.apache.poi.poifs.crypt.EncryptionInfo;\r
+import org.apache.poi.poifs.crypt.HashAlgorithm;\r
 import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;\r
 import org.apache.poi.xwpf.extractor.XWPFWordExtractor;\r
 import org.apache.poi.xwpf.usermodel.XWPFDocument;\r
@@ -33,8 +34,8 @@ public class TestXWPFBugs {
         // Check the encryption details\r
         EncryptionInfo info = new EncryptionInfo(filesystem);\r
         assertEquals(128, info.getHeader().getKeySize());\r
-        assertEquals(EncryptionHeader.ALGORITHM_AES_128, info.getHeader().getAlgorithm());\r
-        assertEquals(EncryptionHeader.HASH_SHA1, info.getHeader().getHashAlgorithm());\r
+        assertEquals(CipherAlgorithm.aes128, info.getHeader().getCipherAlgorithm());\r
+        assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());\r
 \r
         // Check it can be decoded\r
         Decryptor d = Decryptor.getInstance(info);             \r
@@ -67,8 +68,8 @@ public class TestXWPFBugs {
         EncryptionInfo info = new EncryptionInfo(filesystem);\r
         assertEquals(16, info.getHeader().getBlockSize());\r
         assertEquals(256, info.getHeader().getKeySize());\r
-        assertEquals(EncryptionHeader.ALGORITHM_AES_256, info.getHeader().getAlgorithm());\r
-        assertEquals(EncryptionHeader.HASH_SHA1, info.getHeader().getHashAlgorithm());\r
+        assertEquals(CipherAlgorithm.aes256, info.getHeader().getCipherAlgorithm());\r
+        assertEquals(HashAlgorithm.sha1, info.getHeader().getHashAlgorithmEx());\r
 \r
         // Check it can be decoded\r
         Decryptor d = Decryptor.getInstance(info);             \r
diff --git a/src/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java b/src/testcases/org/apache/poi/poifs/crypt/AllPOIFSCryptoTests.java
deleted file mode 100644 (file)
index d7aef10..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/* ====================================================================
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-==================================================================== */
-
-package org.apache.poi.poifs.crypt;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-
-/**
- * Tests for org.apache.poi.poifs.crypt
- *
- * @author Gary King
- */
-public final class AllPOIFSCryptoTests {
-
-    public static Test suite() {
-        TestSuite result = new TestSuite(AllPOIFSCryptoTests.class.getName());
-        result.addTestSuite(TestDecryptor.class);
-        result.addTestSuite(TestEncryptionInfo.class);
-        return result;
-    }
-}
\ No newline at end of file
diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java b/src/testcases/org/apache/poi/poifs/crypt/TestDecryptor.java
deleted file mode 100644 (file)
index dcef8d3..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-/* ====================================================================
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-==================================================================== */
-package org.apache.poi.poifs.crypt;
-
-import junit.framework.TestCase;
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-/**
- *  @author Maxim Valyanskiy
- *  @author Gary King
- */
-public class TestDecryptor extends TestCase {
-    public void testPasswordVerification() throws IOException, GeneralSecurityException {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        Decryptor d = Decryptor.getInstance(info);
-
-        assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD));
-    }
-
-    public void testDecrypt() throws IOException, GeneralSecurityException {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        Decryptor d = Decryptor.getInstance(info);
-
-        d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
-
-        zipOk(fs, d);
-    }
-
-    public void testAgile() throws IOException, GeneralSecurityException {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        assertTrue(info.getVersionMajor() == 4 && info.getVersionMinor() == 4);
-
-        Decryptor d = Decryptor.getInstance(info);
-
-        assertTrue(d.verifyPassword(Decryptor.DEFAULT_PASSWORD));
-
-        zipOk(fs, d);
-    }
-
-    private void zipOk(POIFSFileSystem fs, Decryptor d) throws IOException, GeneralSecurityException {
-        ZipInputStream zin = new ZipInputStream(d.getDataStream(fs));
-
-        while (true) {
-            ZipEntry entry = zin.getNextEntry();
-            if (entry==null) {
-                break;
-            }
-
-            while (zin.available()>0) {
-                zin.skip(zin.available());
-            }
-        }
-    }
-    public void testDataLength() throws Exception {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_agile.docx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        Decryptor d = Decryptor.getInstance(info);
-
-        d.verifyPassword(Decryptor.DEFAULT_PASSWORD);
-
-        InputStream is = d.getDataStream(fs);
-
-        long len = d.getLength();
-        assertEquals(12810, len);
-
-        byte[] buf = new byte[(int)len];
-
-        is.read(buf);
-
-        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(buf));
-
-        while (true) {
-            ZipEntry entry = zin.getNextEntry();
-            if (entry==null) {
-                break;
-            }
-
-            while (zin.available()>0) {
-                zin.skip(zin.available());
-            }
-        }
-    }
-
-}
diff --git a/src/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java b/src/testcases/org/apache/poi/poifs/crypt/TestEncryptionInfo.java
deleted file mode 100644 (file)
index 7869183..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/* ====================================================================
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-==================================================================== */
-package org.apache.poi.poifs.crypt;
-
-import junit.framework.TestCase;
-import org.apache.poi.POIDataSamples;
-import org.apache.poi.poifs.filesystem.POIFSFileSystem;
-
-import java.io.IOException;
-
-/**
- *  @author Maxim Valyanskiy
- */
-public class TestEncryptionInfo extends TestCase {
-    public void testEncryptionInfo() throws IOException {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protect.xlsx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        assertEquals(3, info.getVersionMajor());
-        assertEquals(2, info.getVersionMinor());
-
-        assertEquals(EncryptionHeader.ALGORITHM_AES_128, info.getHeader().getAlgorithm());
-        assertEquals(EncryptionHeader.HASH_SHA1, info.getHeader().getHashAlgorithm());
-        assertEquals(128, info.getHeader().getKeySize());
-        assertEquals(32, info.getVerifier().getVerifierHash().length);
-        assertEquals(EncryptionHeader.PROVIDER_AES, info.getHeader().getProviderType());                
-        assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName());
-    }
-    
-    public void testEncryptionInfoSHA512() throws Exception {
-        POIFSFileSystem fs = new POIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("protected_sha512.xlsx"));
-
-        EncryptionInfo info = new EncryptionInfo(fs);
-
-        assertEquals(4, info.getVersionMajor());
-        assertEquals(4, info.getVersionMinor());
-
-        assertEquals(EncryptionHeader.ALGORITHM_AES_256, info.getHeader().getAlgorithm());
-        assertEquals(EncryptionHeader.HASH_SHA512, info.getHeader().getHashAlgorithm());
-        assertEquals(256, info.getHeader().getKeySize());
-        assertEquals(64, info.getVerifier().getVerifierHash().length);
-        assertEquals(EncryptionHeader.PROVIDER_AES, info.getHeader().getProviderType());                
-//        assertEquals("Microsoft Enhanced RSA and AES Cryptographic Provider", info.getHeader().getCspName());
-    }
-}