Search in sources :

Example 11 with EncryptedDocumentException

use of org.apache.poi.EncryptedDocumentException in project poi by apache.

the class DataSpaceMapUtils method createEncryptionEntry.

public static DocumentEntry createEncryptionEntry(DirectoryEntry dir, String path, EncryptionRecord out) throws IOException {
    String[] parts = path.split("/");
    for (int i = 0; i < parts.length - 1; i++) {
        dir = dir.hasEntry(parts[i]) ? (DirectoryEntry) dir.getEntry(parts[i]) : dir.createDirectory(parts[i]);
    }
    final byte[] buf = new byte[5000];
    LittleEndianByteArrayOutputStream bos = new LittleEndianByteArrayOutputStream(buf, 0);
    out.write(bos);
    String fileName = parts[parts.length - 1];
    if (dir.hasEntry(fileName)) {
        dir.getEntry(fileName).delete();
    }
    return dir.createDocument(fileName, bos.getWriteIndex(), new POIFSWriterListener() {

        public void processPOIFSWriterEvent(POIFSWriterEvent event) {
            try {
                event.getStream().write(buf, 0, event.getLimit());
            } catch (IOException e) {
                throw new EncryptedDocumentException(e);
            }
        }
    });
}
Also used : LittleEndianByteArrayOutputStream(org.apache.poi.util.LittleEndianByteArrayOutputStream) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) POIFSWriterListener(org.apache.poi.poifs.filesystem.POIFSWriterListener) IOException(java.io.IOException) DirectoryEntry(org.apache.poi.poifs.filesystem.DirectoryEntry) POIFSWriterEvent(org.apache.poi.poifs.filesystem.POIFSWriterEvent)

Example 12 with EncryptedDocumentException

use of org.apache.poi.EncryptedDocumentException in project poi by apache.

the class ChunkedCipherInputStream method read.

private int read(byte[] b, int off, int len, boolean readPlain) throws IOException {
    int total = 0;
    if (available() <= 0) {
        return -1;
    }
    final int chunkMask = getChunkMask();
    while (len > 0) {
        if (!chunkIsValid) {
            try {
                nextChunk();
                chunkIsValid = true;
            } catch (GeneralSecurityException e) {
                throw new EncryptedDocumentException(e.getMessage(), e);
            }
        }
        int count = (int) (chunk.length - (pos & chunkMask));
        int avail = available();
        if (avail == 0) {
            return total;
        }
        count = Math.min(avail, Math.min(count, len));
        System.arraycopy(readPlain ? plain : chunk, (int) (pos & chunkMask), b, off, count);
        off += count;
        len -= count;
        pos += count;
        if ((pos & chunkMask) == 0) {
            chunkIsValid = false;
        }
        total += count;
    }
    return total;
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException)

Example 13 with EncryptedDocumentException

use of org.apache.poi.EncryptedDocumentException in project poi by apache.

the class BinaryRC4Decryptor method verifyPassword.

@Override
public boolean verifyPassword(String password) {
    EncryptionVerifier ver = getEncryptionInfo().getVerifier();
    SecretKey skey = generateSecretKey(password, ver);
    try {
        Cipher cipher = initCipherForBlock(null, 0, getEncryptionInfo(), skey, Cipher.DECRYPT_MODE);
        byte[] encryptedVerifier = ver.getEncryptedVerifier();
        byte[] verifier = new byte[encryptedVerifier.length];
        cipher.update(encryptedVerifier, 0, encryptedVerifier.length, verifier);
        setVerifier(verifier);
        byte[] encryptedVerifierHash = ver.getEncryptedVerifierHash();
        byte[] verifierHash = cipher.doFinal(encryptedVerifierHash);
        HashAlgorithm hashAlgo = ver.getHashAlgorithm();
        MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
        byte[] calcVerifierHash = hashAlg.digest(verifier);
        if (Arrays.equals(calcVerifierHash, verifierHash)) {
            setSecretKey(skey);
            return true;
        }
    } catch (GeneralSecurityException e) {
        throw new EncryptedDocumentException(e);
    }
    return false;
}
Also used : SecretKey(javax.crypto.SecretKey) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 14 with EncryptedDocumentException

use of org.apache.poi.EncryptedDocumentException in project poi by apache.

the class XWPFSettings method setEnforcementEditValue.

/**
     * Enforces the protection with the option specified by passed editValue and password.<br/>
     * <br/>
     * sample snippet from settings.xml
     * <pre>
     *   &lt;w:documentProtection w:edit=&quot;[passed editValue]&quot; w:enforcement=&quot;1&quot;
     *       w:cryptProviderType=&quot;rsaAES&quot; w:cryptAlgorithmClass=&quot;hash&quot;
     *       w:cryptAlgorithmType=&quot;typeAny&quot; w:cryptAlgorithmSid=&quot;14&quot;
     *       w:cryptSpinCount=&quot;100000&quot; w:hash=&quot;...&quot; w:salt=&quot;....&quot;
     *   /&gt;
     * </pre>
     *
     * @param editValue the protection type
     * @param password  the plaintext password, if null no password will be applied
     * @param hashAlgo  the hash algorithm - only md2, m5, sha1, sha256, sha384 and sha512 are supported.
     *                  if null, it will default default to sha1
     */
public void setEnforcementEditValue(org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect.Enum editValue, String password, HashAlgorithm hashAlgo) {
    safeGetDocumentProtection().setEnforcement(STOnOff.X_1);
    safeGetDocumentProtection().setEdit(editValue);
    if (password == null) {
        if (safeGetDocumentProtection().isSetCryptProviderType()) {
            safeGetDocumentProtection().unsetCryptProviderType();
        }
        if (safeGetDocumentProtection().isSetCryptAlgorithmClass()) {
            safeGetDocumentProtection().unsetCryptAlgorithmClass();
        }
        if (safeGetDocumentProtection().isSetCryptAlgorithmType()) {
            safeGetDocumentProtection().unsetCryptAlgorithmType();
        }
        if (safeGetDocumentProtection().isSetCryptAlgorithmSid()) {
            safeGetDocumentProtection().unsetCryptAlgorithmSid();
        }
        if (safeGetDocumentProtection().isSetSalt()) {
            safeGetDocumentProtection().unsetSalt();
        }
        if (safeGetDocumentProtection().isSetCryptSpinCount()) {
            safeGetDocumentProtection().unsetCryptSpinCount();
        }
        if (safeGetDocumentProtection().isSetHash()) {
            safeGetDocumentProtection().unsetHash();
        }
    } else {
        final STCryptProv.Enum providerType;
        final int sid;
        if (hashAlgo == null) {
            hashAlgo = HashAlgorithm.sha1;
        }
        switch(hashAlgo) {
            case md2:
                providerType = STCryptProv.RSA_FULL;
                sid = 1;
                break;
            case md4:
                providerType = STCryptProv.RSA_FULL;
                sid = 2;
                break;
            case md5:
                providerType = STCryptProv.RSA_FULL;
                sid = 3;
                break;
            case sha1:
                providerType = STCryptProv.RSA_FULL;
                sid = 4;
                break;
            case sha256:
                providerType = STCryptProv.RSA_AES;
                sid = 12;
                break;
            case sha384:
                providerType = STCryptProv.RSA_AES;
                sid = 13;
                break;
            case sha512:
                providerType = STCryptProv.RSA_AES;
                sid = 14;
                break;
            default:
                throw new EncryptedDocumentException("Hash algorithm '" + hashAlgo + "' is not supported for document write protection.");
        }
        SecureRandom random = new SecureRandom();
        byte[] salt = random.generateSeed(16);
        // Iterations specifies the number of times the hashing function shall be iteratively run (using each
        // iteration's result as the input for the next iteration).
        int spinCount = 100000;
        String legacyHash = CryptoFunctions.xorHashPasswordReversed(password);
        // Implementation Notes List:
        // --> In this third stage, the reversed byte order legacy hash from the second stage shall
        //     be converted to Unicode hex string representation
        byte[] hash = CryptoFunctions.hashPassword(legacyHash, hashAlgo, salt, spinCount, false);
        safeGetDocumentProtection().setSalt(salt);
        safeGetDocumentProtection().setHash(hash);
        safeGetDocumentProtection().setCryptSpinCount(BigInteger.valueOf(spinCount));
        safeGetDocumentProtection().setCryptAlgorithmType(STAlgType.TYPE_ANY);
        safeGetDocumentProtection().setCryptAlgorithmClass(STAlgClass.HASH);
        safeGetDocumentProtection().setCryptProviderType(providerType);
        safeGetDocumentProtection().setCryptAlgorithmSid(BigInteger.valueOf(sid));
    }
}
Also used : STCryptProv(org.openxmlformats.schemas.wordprocessingml.x2006.main.STCryptProv) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) SecureRandom(java.security.SecureRandom)

Example 15 with EncryptedDocumentException

use of org.apache.poi.EncryptedDocumentException in project poi by apache.

the class HSLFSlideShowEncrypted method removeEncryptionRecord.

protected static Record[] removeEncryptionRecord(Record[] records) {
    int deaSlideId = -1;
    int deaOffset = -1;
    PersistPtrHolder ptr = null;
    UserEditAtom uea = null;
    List<Record> recordList = new ArrayList<Record>();
    for (Record r : records) {
        if (r instanceof DocumentEncryptionAtom) {
            deaOffset = ((DocumentEncryptionAtom) r).getLastOnDiskOffset();
            continue;
        } else if (r instanceof UserEditAtom) {
            uea = (UserEditAtom) r;
            deaSlideId = uea.getEncryptSessionPersistIdRef();
            uea.setEncryptSessionPersistIdRef(-1);
        } else if (r instanceof PersistPtrHolder) {
            ptr = (PersistPtrHolder) r;
        }
        recordList.add(r);
    }
    if (ptr == null || uea == null) {
        throw new EncryptedDocumentException("UserEditAtom or PersistPtrholder not found.");
    }
    if (deaSlideId == -1 && deaOffset == -1) {
        return records;
    }
    TreeMap<Integer, Integer> tm = new TreeMap<Integer, Integer>(ptr.getSlideLocationsLookup());
    ptr.clear();
    int maxSlideId = -1;
    for (Map.Entry<Integer, Integer> me : tm.entrySet()) {
        if (me.getKey() == deaSlideId || me.getValue() == deaOffset) {
            continue;
        }
        ptr.addSlideLookup(me.getKey(), me.getValue());
        maxSlideId = Math.max(me.getKey(), maxSlideId);
    }
    uea.setMaxPersistWritten(maxSlideId);
    records = recordList.toArray(new Record[recordList.size()]);
    return records;
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) PersistPtrHolder(org.apache.poi.hslf.record.PersistPtrHolder) ArrayList(java.util.ArrayList) TreeMap(java.util.TreeMap) DocumentEncryptionAtom(org.apache.poi.hslf.record.DocumentEncryptionAtom) Record(org.apache.poi.hslf.record.Record) PositionDependentRecord(org.apache.poi.hslf.record.PositionDependentRecord) UserEditAtom(org.apache.poi.hslf.record.UserEditAtom) Map(java.util.Map) NavigableMap(java.util.NavigableMap) TreeMap(java.util.TreeMap)

Aggregations

EncryptedDocumentException (org.apache.poi.EncryptedDocumentException)33 GeneralSecurityException (java.security.GeneralSecurityException)16 Cipher (javax.crypto.Cipher)10 SecretKey (javax.crypto.SecretKey)9 MessageDigest (java.security.MessageDigest)8 IOException (java.io.IOException)6 HashAlgorithm (org.apache.poi.poifs.crypt.HashAlgorithm)4 LittleEndianByteArrayOutputStream (org.apache.poi.util.LittleEndianByteArrayOutputStream)4 Test (org.junit.Test)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 DigestException (java.security.DigestException)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 NavigableMap (java.util.NavigableMap)2 NoSuchElementException (java.util.NoSuchElementException)2 TreeMap (java.util.TreeMap)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 PersistPtrHolder (org.apache.poi.hslf.record.PersistPtrHolder)2 PositionDependentRecord (org.apache.poi.hslf.record.PositionDependentRecord)2