Search in sources :

Example 31 with EncryptedDocumentException

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

the class BinaryRC4Encryptor method confirmPassword.

@Override
public void confirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) {
    BinaryRC4EncryptionVerifier ver = (BinaryRC4EncryptionVerifier) getEncryptionInfo().getVerifier();
    ver.setSalt(verifierSalt);
    SecretKey skey = BinaryRC4Decryptor.generateSecretKey(password, ver);
    setSecretKey(skey);
    try {
        Cipher cipher = BinaryRC4Decryptor.initCipherForBlock(null, 0, getEncryptionInfo(), skey, Cipher.ENCRYPT_MODE);
        byte[] encryptedVerifier = new byte[16];
        cipher.update(verifier, 0, 16, encryptedVerifier);
        ver.setEncryptedVerifier(encryptedVerifier);
        HashAlgorithm hashAlgo = ver.getHashAlgorithm();
        MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
        byte[] calcVerifierHash = hashAlg.digest(verifier);
        byte[] encryptedVerifierHash = cipher.doFinal(calcVerifierHash);
        ver.setEncryptedVerifierHash(encryptedVerifierHash);
    } catch (GeneralSecurityException e) {
        throw new EncryptedDocumentException("Password confirmation failed", e);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest) HashAlgorithm(org.apache.poi.poifs.crypt.HashAlgorithm)

Example 32 with EncryptedDocumentException

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

the class CryptoFunctions method getCipher.

/**
     * Initialize a new cipher object with the given cipher properties
     * If the given algorithm is not implemented in the JCE, it will try to load it from the bouncy castle
     * provider.
     *
     * @param key the secrect key
     * @param cipherAlgorithm the cipher algorithm
     * @param chain the chaining mode
     * @param vec the initialization vector (IV), can be null
     * @param cipherMode Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE
     * @param padding the padding (null = NOPADDING, ANSIX923Padding, PKCS5Padding, PKCS7Padding, ISO10126Padding, ...)
     * @return the requested cipher
     * @throws GeneralSecurityException
     * @throws EncryptedDocumentException if the initialization failed or if an algorithm was specified,
     *   which depends on a missing bouncy castle provider 
     */
public static Cipher getCipher(Key key, CipherAlgorithm cipherAlgorithm, ChainingMode chain, byte[] vec, int cipherMode, String padding) {
    int keySizeInBytes = key.getEncoded().length;
    if (padding == null)
        padding = "NoPadding";
    try {
        // Ensure the JCE policies files allow for this sized key
        if (Cipher.getMaxAllowedKeyLength(cipherAlgorithm.jceId) < keySizeInBytes * 8) {
            throw new EncryptedDocumentException("Export Restrictions in place - please install JCE Unlimited Strength Jurisdiction Policy files");
        }
        Cipher cipher;
        if (cipherAlgorithm == CipherAlgorithm.rc4) {
            cipher = Cipher.getInstance(cipherAlgorithm.jceId);
        } else if (cipherAlgorithm.needsBouncyCastle) {
            registerBouncyCastle();
            cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding, "BC");
        } else {
            cipher = Cipher.getInstance(cipherAlgorithm.jceId + "/" + chain.jceId + "/" + padding);
        }
        if (vec == null) {
            cipher.init(cipherMode, key);
        } else {
            AlgorithmParameterSpec aps;
            if (cipherAlgorithm == CipherAlgorithm.rc2) {
                aps = new RC2ParameterSpec(key.getEncoded().length * 8, vec);
            } else {
                aps = new IvParameterSpec(vec);
            }
            cipher.init(cipherMode, key, aps);
        }
        return cipher;
    } catch (GeneralSecurityException e) {
        throw new EncryptedDocumentException(e);
    }
}
Also used : EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) GeneralSecurityException(java.security.GeneralSecurityException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 33 with EncryptedDocumentException

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

the class HSSFWorkbook method encryptBytes.

@SuppressWarnings("resource")
protected void encryptBytes(byte[] buf) {
    int initialOffset = 0;
    FilePassRecord fpr = null;
    for (Record r : workbook.getRecords()) {
        initialOffset += r.getRecordSize();
        if (r instanceof FilePassRecord) {
            fpr = (FilePassRecord) r;
            break;
        }
    }
    if (fpr == null) {
        return;
    }
    // NOSONAR
    LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0);
    // NOSONAR
    LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0);
    Encryptor enc = fpr.getEncryptionInfo().getEncryptor();
    enc.setChunkSize(Biff8DecryptingStream.RC4_REKEYING_INTERVAL);
    byte[] tmp = new byte[1024];
    try {
        ChunkedCipherOutputStream os = enc.getDataStream(leos, initialOffset);
        int totalBytes = 0;
        while (totalBytes < buf.length) {
            plain.read(tmp, 0, 4);
            final int sid = LittleEndian.getUShort(tmp, 0);
            final int len = LittleEndian.getUShort(tmp, 2);
            boolean isPlain = Biff8DecryptingStream.isNeverEncryptedRecord(sid);
            os.setNextRecordSize(len, isPlain);
            os.writePlain(tmp, 0, 4);
            if (sid == BoundSheetRecord.sid) {
                // special case for the field_1_position_of_BOF (=lbPlyPos) field of
                // the BoundSheet8 record which must be unencrypted
                byte[] bsrBuf = new byte[len];
                plain.readFully(bsrBuf);
                os.writePlain(bsrBuf, 0, 4);
                os.write(bsrBuf, 4, len - 4);
            } else {
                int todo = len;
                while (todo > 0) {
                    int nextLen = Math.min(todo, tmp.length);
                    plain.readFully(tmp, 0, nextLen);
                    if (isPlain) {
                        os.writePlain(tmp, 0, nextLen);
                    } else {
                        os.write(tmp, 0, nextLen);
                    }
                    todo -= nextLen;
                }
            }
            totalBytes += 4 + len;
        }
        os.close();
    } catch (Exception e) {
        throw new EncryptedDocumentException(e);
    }
}
Also used : FilePassRecord(org.apache.poi.hssf.record.FilePassRecord) LittleEndianByteArrayOutputStream(org.apache.poi.util.LittleEndianByteArrayOutputStream) ChunkedCipherOutputStream(org.apache.poi.poifs.crypt.ChunkedCipherOutputStream) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException) LittleEndianByteArrayInputStream(org.apache.poi.util.LittleEndianByteArrayInputStream) UnknownRecord(org.apache.poi.hssf.record.UnknownRecord) RecalcIdRecord(org.apache.poi.hssf.record.RecalcIdRecord) EscherBSERecord(org.apache.poi.ddf.EscherBSERecord) Record(org.apache.poi.hssf.record.Record) AbstractEscherHolderRecord(org.apache.poi.hssf.record.AbstractEscherHolderRecord) BoundSheetRecord(org.apache.poi.hssf.record.BoundSheetRecord) EscherBlipRecord(org.apache.poi.ddf.EscherBlipRecord) DrawingGroupRecord(org.apache.poi.hssf.record.DrawingGroupRecord) BackupRecord(org.apache.poi.hssf.record.BackupRecord) EscherRecord(org.apache.poi.ddf.EscherRecord) NameRecord(org.apache.poi.hssf.record.NameRecord) LabelSSTRecord(org.apache.poi.hssf.record.LabelSSTRecord) LabelRecord(org.apache.poi.hssf.record.LabelRecord) FilePassRecord(org.apache.poi.hssf.record.FilePassRecord) FontRecord(org.apache.poi.hssf.record.FontRecord) SSTRecord(org.apache.poi.hssf.record.SSTRecord) ExtendedFormatRecord(org.apache.poi.hssf.record.ExtendedFormatRecord) Encryptor(org.apache.poi.poifs.crypt.Encryptor) FileNotFoundException(java.io.FileNotFoundException) OldExcelFormatException(org.apache.poi.hssf.OldExcelFormatException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) EncryptedDocumentException(org.apache.poi.EncryptedDocumentException)

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