Java Code Examples for org.apache.poi.poifs.crypt.EncryptionInfo

The following examples show how to use org.apache.poi.poifs.crypt.EncryptionInfo. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: easyexcel   Source File: WriteContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
private POIFSFileSystem openFileSystemAndEncrypt(File file) throws Exception {
    POIFSFileSystem fileSystem = new POIFSFileSystem();
    Encryptor encryptor = new EncryptionInfo(EncryptionMode.standard).getEncryptor();
    encryptor.confirmPassword(writeWorkbookHolder.getPassword());
    OPCPackage opcPackage = null;
    try {
        opcPackage = OPCPackage.open(file, PackageAccess.READ_WRITE);
        OutputStream outputStream = encryptor.getDataStream(fileSystem);
        opcPackage.save(outputStream);
    } finally {
        if (opcPackage != null) {
            opcPackage.close();
        }
    }
    return fileSystem;
}
 
Example 2
Source Project: easyexcel   Source File: Poi3Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void Encryption() throws Exception {
    String file = TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx";
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword("foobaa");
    OPCPackage opc = OPCPackage.open(new File(file), PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();

    // Write out the encrypted version
    FileOutputStream fos = new FileOutputStream("D:\\test\\99999999999.xlsx");
    fs.writeFilesystem(fos);
    fos.close();
    fs.close();

}
 
Example 3
Source Project: lams   Source File: BinaryRC4Encryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {
    DataSpaceMapUtils.addDefaultDataSpace(dir);
    final EncryptionInfo info = getEncryptionInfo();
    final BinaryRC4EncryptionHeader header = (BinaryRC4EncryptionHeader)info.getHeader();
    final BinaryRC4EncryptionVerifier verifier = (BinaryRC4EncryptionVerifier)info.getVerifier();
    EncryptionRecord er = new EncryptionRecord() {
        @Override
        public void write(LittleEndianByteArrayOutputStream bos) {
            bos.writeShort(info.getVersionMajor());
            bos.writeShort(info.getVersionMinor());
            header.write(bos);
            verifier.write(bos);
        }
    };
    DataSpaceMapUtils.createEncryptionEntry(dir, "EncryptionInfo", er);
}
 
Example 4
Source Project: lams   Source File: StandardEncryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {
    final EncryptionInfo info = getEncryptionInfo();
    final StandardEncryptionHeader header = (StandardEncryptionHeader)info.getHeader();
    final StandardEncryptionVerifier verifier = (StandardEncryptionVerifier)info.getVerifier();
    
    EncryptionRecord er = new EncryptionRecord(){
        @Override
        public void write(LittleEndianByteArrayOutputStream bos) {
            bos.writeShort(info.getVersionMajor());
            bos.writeShort(info.getVersionMinor());
            bos.writeInt(info.getEncryptionFlags());
            header.write(bos);
            verifier.write(bos);
        }
    };
    
    createEncryptionEntry(dir, "EncryptionInfo", er);
    
    // TODO: any properties???
}
 
Example 5
Source Project: lams   Source File: CryptoAPIEncryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected void createEncryptionInfoEntry(DirectoryNode dir) throws IOException {
    DataSpaceMapUtils.addDefaultDataSpace(dir);
    final EncryptionInfo info = getEncryptionInfo();
    final CryptoAPIEncryptionHeader header = (CryptoAPIEncryptionHeader)getEncryptionInfo().getHeader();
    final CryptoAPIEncryptionVerifier verifier = (CryptoAPIEncryptionVerifier)getEncryptionInfo().getVerifier();
    EncryptionRecord er = new EncryptionRecord() {
        @Override
        public void write(LittleEndianByteArrayOutputStream bos) {
            bos.writeShort(info.getVersionMajor());
            bos.writeShort(info.getVersionMinor());
            header.write(bos);
            verifier.write(bos);
        }
    };
    DataSpaceMapUtils.createEncryptionEntry(dir, "EncryptionInfo", er);
}
 
Example 6
Source Project: lams   Source File: CryptoAPIDecryptor.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static Cipher initCipherForBlock(Cipher cipher, int block,
    EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
    EncryptionVerifier ver = encryptionInfo.getVerifier();
    HashAlgorithm hashAlgo = ver.getHashAlgorithm();
    byte blockKey[] = new byte[4];
    LittleEndian.putUInt(blockKey, 0, block);
    MessageDigest hashAlg = CryptoFunctions.getMessageDigest(hashAlgo);
    hashAlg.update(skey.getEncoded());
    byte encKey[] = hashAlg.digest(blockKey);
    EncryptionHeader header = encryptionInfo.getHeader();
    int keyBits = header.getKeySize();
    encKey = CryptoFunctions.getBlock0(encKey, keyBits / 8);
    if (keyBits == 40) {
        encKey = CryptoFunctions.getBlock0(encKey, 16);
    }
    SecretKey key = new SecretKeySpec(encKey, skey.getAlgorithm());
    if (cipher == null) {
        cipher = CryptoFunctions.getCipher(key, header.getCipherAlgorithm(), null, null, encryptMode);
    } else {
        cipher.init(encryptMode, key);
    }
    return cipher;
}
 
Example 7
Source Project: lams   Source File: FilePassRecord.java    License: GNU General Public License v2.0 6 votes vote down vote up
public FilePassRecord(RecordInputStream in) {
	encryptionType = in.readUShort();
	
	EncryptionMode preferredMode;
       switch (encryptionType) {
           case ENCRYPTION_XOR:
               preferredMode = EncryptionMode.xor;
               break;
           case ENCRYPTION_OTHER:
               preferredMode = EncryptionMode.cryptoAPI;
               break;
           default:
               throw new EncryptedDocumentException("invalid encryption type");
       }
	
	try {
           encryptionInfo = new EncryptionInfo(in, preferredMode);
       } catch (IOException e) {
           throw new EncryptedDocumentException(e);
       }
}
 
Example 8
public RecordInputStream createDecryptingStream(InputStream original) {
	FilePassRecord fpr = _filePassRec;
	String userPassword = Biff8EncryptionKey.getCurrentUserPassword();
	if (userPassword == null) {
	    userPassword = Decryptor.DEFAULT_PASSWORD;
	}

	EncryptionInfo info = fpr.getEncryptionInfo();
          try {
              if (!info.getDecryptor().verifyPassword(userPassword)) {
                  throw new EncryptedDocumentException(
                          (Decryptor.DEFAULT_PASSWORD.equals(userPassword) ? "Default" : "Supplied")
                          + " password is invalid for salt/verifier/verifierHash");
              }
          } catch (GeneralSecurityException e) {
              throw new EncryptedDocumentException(e);
          }

	return new RecordInputStream(original, info, _initialRecordsSize);
}
 
Example 9
Source Project: lams   Source File: DocumentFactoryHelper.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Wrap the OLE2 data in the NPOIFSFileSystem into a decrypted stream by using
 * the given password.
 *
 * @param fs The OLE2 stream for the document
 * @param password The password, null if the default password should be used
 * @return A stream for reading the decrypted data
 * @throws IOException If an error occurs while decrypting or if the password does not match
 */
public static InputStream getDecryptedStream(final NPOIFSFileSystem fs, String password)
        throws IOException {
    EncryptionInfo info = new EncryptionInfo(fs);
    Decryptor d = Decryptor.getInstance(info);

    try {
        boolean passwordCorrect = false;
        if (password != null && d.verifyPassword(password)) {
            passwordCorrect = true;
        }
        if (!passwordCorrect && d.verifyPassword(Decryptor.DEFAULT_PASSWORD)) {
            passwordCorrect = true;
        }

        if (passwordCorrect) {
            // wrap the stream in a FilterInputStream to close the NPOIFSFileSystem
            // as well when the resulting OPCPackage is closed
            return new FilterInputStream(d.getDataStream(fs.getRoot())) {
                @Override
                public void close() throws IOException {
                    fs.close();

                    super.close();
                }
            };
        } else {
            if (password != null)
                throw new EncryptedDocumentException("Password incorrect");
            else
                throw new EncryptedDocumentException("The supplied spreadsheet is protected, but no password was supplied");
        }
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}
 
Example 10
@Override
public void initialize(EncryptionInfo info, LittleEndianInput dis)
throws IOException {
    info.setHeader(new XOREncryptionHeader());
    info.setVerifier(new XOREncryptionVerifier(dis));
    Decryptor dec = new XORDecryptor();
    dec.setEncryptionInfo(info);
    info.setDecryptor(dec);
    Encryptor enc = new XOREncryptor();
    enc.setEncryptionInfo(info);
    info.setEncryptor(enc);
}
 
Example 11
@Override
public void initialize(EncryptionInfo info,
    CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm,
    int keyBits, int blockSize, ChainingMode chainingMode) {
    info.setHeader(new XOREncryptionHeader());
    info.setVerifier(new XOREncryptionVerifier());
    Decryptor dec = new XORDecryptor();
    dec.setEncryptionInfo(info);
    info.setDecryptor(dec);
    Encryptor enc = new XOREncryptor();
    enc.setEncryptionInfo(info);
    info.setEncryptor(enc);
}
 
Example 12
/**
 * initialize the builder from a stream
 */
@Override
public void initialize(EncryptionInfo info, LittleEndianInput dis) throws IOException {
    /* int hSize = */ dis.readInt();
    StandardEncryptionHeader header = new StandardEncryptionHeader(dis);
    info.setHeader(header);
    info.setVerifier(new StandardEncryptionVerifier(dis, header));

    if (info.getVersionMinor() == 2 && (info.getVersionMajor() == 3 || info.getVersionMajor() == 4)) {
        StandardDecryptor dec = new StandardDecryptor();
        dec.setEncryptionInfo(info);
        info.setDecryptor(dec);
    }
}
 
Example 13
Source Project: lams   Source File: CryptoAPIEncryptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected Cipher initCipherForBlock(Cipher cipher, int block, boolean lastChunk)
throws IOException, GeneralSecurityException {
    flush();
    EncryptionInfo ei = getEncryptionInfo();
    SecretKey sk = getSecretKey();
    return CryptoAPIDecryptor.initCipherForBlock(cipher, block, ei, sk, Cipher.ENCRYPT_MODE);
}
 
Example 14
Source Project: lams   Source File: CryptoAPIDecryptor.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Cipher initCipherForBlock(Cipher cipher, int block)
throws GeneralSecurityException {
    EncryptionInfo ei = getEncryptionInfo();
    SecretKey sk = getSecretKey();
    return initCipherForBlock(cipher, block, ei, sk, Cipher.DECRYPT_MODE);
}
 
Example 15
Source Project: lams   Source File: HSSFWorkbook.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void updateEncryptionInfo() {
    // make sure, that we've read all the streams ...
    readProperties();
    FilePassRecord fpr = (FilePassRecord)workbook.findFirstRecordBySid(FilePassRecord.sid);

    String password = Biff8EncryptionKey.getCurrentUserPassword();
    WorkbookRecordList wrl = workbook.getWorkbookRecordList();
    if (password == null) {
        if (fpr != null) {
            // need to remove password data
            wrl.remove(fpr);
        }
    } else {
        // create password record
        if (fpr == null) {
            fpr = new FilePassRecord(EncryptionMode.cryptoAPI);
            wrl.add(1, fpr);
        }

        // check if the password has been changed
        EncryptionInfo ei = fpr.getEncryptionInfo();
        EncryptionVerifier ver = ei.getVerifier();
        byte encVer[] = ver.getEncryptedVerifier();
        Decryptor dec = ei.getDecryptor();
        Encryptor enc = ei.getEncryptor();
        try {
            if (encVer == null || !dec.verifyPassword(password)) {
                enc.confirmPassword(password);
            } else {
                byte verifier[] = dec.getVerifier();
                byte salt[] = ver.getSalt();
                enc.confirmPassword(password, null, null, verifier, salt, null);
            }
        } catch (GeneralSecurityException e) {
            throw new EncryptedDocumentException("can't validate/update encryption setting", e);
        }
    }
}
 
Example 16
Source Project: lams   Source File: RecordInputStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
public RecordInputStream(InputStream in, EncryptionInfo key, int initialOffset) throws RecordFormatException {
	if (key == null) {
		_dataInput = getLEI(in);
		_bhi = new SimpleHeaderInput(in);
	} else {
		Biff8DecryptingStream bds = new Biff8DecryptingStream(in, initialOffset, key);
           _dataInput = bds;
		_bhi = bds;
	}
	_nextSid = readNextSid();
}
 
Example 17
Source Project: myexcel   Source File: AttachmentExportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加密导出
 *
 * @param workbook workbook
 * @param fileName fileName
 * @param response response
 * @param password password
 */
public static void encryptExport(final Workbook workbook, String fileName, HttpServletResponse response, final String password) {
    if (workbook instanceof HSSFWorkbook) {
        throw new IllegalArgumentException("Document encryption for.xls is not supported");
    }
    Path path = null;
    try {
        String suffix = Constants.XLSX;
        path = TempFileOperator.createTempFile("encrypt_temp", suffix);
        workbook.write(Files.newOutputStream(path));

        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        final Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try (OPCPackage opc = OPCPackage.open(path.toFile(), PackageAccess.READ_WRITE);
             OutputStream os = enc.getDataStream(fs)) {
            opc.save(os);
        }
        if (!fileName.endsWith(suffix)) {
            fileName += suffix;
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        setAttachmentConfig(fileName, response);
        fs.writeFilesystem(response.getOutputStream());
    } catch (IOException | InvalidFormatException | GeneralSecurityException e) {
        throw new RuntimeException(e);
    } finally {
        clear(workbook);
        TempFileOperator.deleteTempFile(path);
    }
}
 
Example 18
Source Project: myexcel   Source File: FileExportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加密导出
 *
 * @param workbook workbook
 * @param file     file
 * @param password password
 * @throws Exception Exception
 */
public static void encryptExport(final Workbook workbook, File file, final String password) throws Exception {
    if (workbook instanceof HSSFWorkbook) {
        throw new IllegalArgumentException("Document encryption for.xls is not supported");
    }
    String suffix = Constants.XLSX;
    if (!file.getName().endsWith(suffix)) {
        file = Paths.get(file.getAbsolutePath() + suffix).toFile();
    }
    try (FileOutputStream fos = new FileOutputStream(file)) {
        workbook.write(fos);
        if (workbook instanceof SXSSFWorkbook) {
            ((SXSSFWorkbook) workbook).dispose();
        }

        final POIFSFileSystem fs = new POIFSFileSystem();
        final EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
        final Encryptor enc = info.getEncryptor();
        enc.confirmPassword(password);

        try (OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
             OutputStream os = enc.getDataStream(fs)) {
            opc.save(os);
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
            fs.writeFilesystem(fileOutputStream);
        }
    } finally {
        workbook.close();
    }
}
 
Example 19
Source Project: hadoopoffice   Source File: MSExcelOOXMLSignUtil.java    License: Apache License 2.0 5 votes vote down vote up
private void signEncryptedPackage(InputStream tmpFileInputStream, SignatureConfig sc, String password) throws IOException, InvalidFormatException, FormatNotUnderstoodException, XMLSignatureException, MarshalException {

	POIFSFileSystem poifsTemp = new POIFSFileSystem(tmpFileInputStream);
	EncryptionInfo info = new EncryptionInfo(poifsTemp);
	Decryptor d = Decryptor.getInstance(info);

	try {
		if (!d.verifyPassword(password)) {
			throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx) for signing. Invalid password");
		}
		// signing
		OPCPackage pkg = OPCPackage.open(d.getDataStream(poifsTemp));
		sc.setOpcPackage(pkg);
		
		SignatureInfo si = new SignatureInfo();
		si.setSignatureConfig(sc);
		si.confirmSignature();
		// encrypt again
		Encryptor enc = info.getEncryptor();
		enc.confirmPassword(password);
		POIFSFileSystem poifs = new POIFSFileSystem();
		OutputStream os = enc.getDataStream(poifs);
		pkg.save(os);
		pkg.close();
		if (os!=null) {
			os.close();
		}
		poifs.writeFilesystem(this.finalOutputStream);
		if (poifs!=null) {
			poifs.close();
		}
		if (poifsTemp!=null) {
			poifsTemp.close();
		}
	} catch (GeneralSecurityException e) {
		
		LOG.error(e);
		throw new FormatNotUnderstoodException("Error: Cannot decrypt new Excel file (.xlsx)  for signing.");
	} 
}
 
Example 20
Source Project: lams   Source File: XORDecryptor.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected static Cipher initCipherForBlock(Cipher cipher, int block,
    EncryptionInfo encryptionInfo, SecretKey skey, int encryptMode)
throws GeneralSecurityException {
    return null;
}
 
Example 21
/**
 * initialize the builder from scratch
 */
@Override
public void initialize(EncryptionInfo info, CipherAlgorithm cipherAlgorithm, HashAlgorithm hashAlgorithm, int keyBits, int blockSize, ChainingMode chainingMode) {
    if (cipherAlgorithm == null) {
        cipherAlgorithm = CipherAlgorithm.aes128;
    }
    if (cipherAlgorithm != CipherAlgorithm.aes128 &&
        cipherAlgorithm != CipherAlgorithm.aes192 &&
        cipherAlgorithm != CipherAlgorithm.aes256) {
        throw new EncryptedDocumentException("Standard encryption only supports AES128/192/256.");
    }
    
    if (hashAlgorithm == null) {
        hashAlgorithm = HashAlgorithm.sha1;
    }
    if (hashAlgorithm != HashAlgorithm.sha1) {
        throw new EncryptedDocumentException("Standard encryption only supports SHA-1.");
    }
    if (chainingMode == null) {
        chainingMode = ChainingMode.ecb;
    }
    if (chainingMode != ChainingMode.ecb) {
        throw new EncryptedDocumentException("Standard encryption only supports ECB chaining.");
    }
    if (keyBits == -1) {
        keyBits = cipherAlgorithm.defaultKeySize;
    }
    if (blockSize == -1) {
        blockSize = cipherAlgorithm.blockSize;
    }
    boolean found = false;
    for (int ks : cipherAlgorithm.allowedKeySize) {
        found |= (ks == keyBits);
    }
    if (!found) {
        throw new EncryptedDocumentException("KeySize "+keyBits+" not allowed for Cipher "+ cipherAlgorithm);
    }
    info.setHeader(new StandardEncryptionHeader(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode));
    info.setVerifier(new StandardEncryptionVerifier(cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode));
    StandardDecryptor dec = new StandardDecryptor();
    dec.setEncryptionInfo(info);
    info.setDecryptor(dec);
    StandardEncryptor enc = new StandardEncryptor();
    enc.setEncryptionInfo(info);
    info.setEncryptor(enc);
}
 
Example 22
Source Project: lams   Source File: POIDocument.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * Writes out the standard Document Information Properties (HPSF)
 * @param outFS the NPOIFSFileSystem to write the properties into
 * @param writtenEntries a list of POIFS entries to add the property names too
 * 
 * @throws IOException if an error when writing to the 
 *      {@link NPOIFSFileSystem} occurs
 */
protected void writeProperties(NPOIFSFileSystem outFS, List<String> writtenEntries) throws IOException {
    EncryptionInfo ei = getEncryptionInfo();
    final boolean encryptProps = (ei != null && ei.isDocPropsEncrypted());
    NPOIFSFileSystem fs = (encryptProps) ? new NPOIFSFileSystem() : outFS;
    
    SummaryInformation si = getSummaryInformation();
    if (si != null) {
        writePropertySet(SummaryInformation.DEFAULT_STREAM_NAME, si, fs);
        if(writtenEntries != null) {
            writtenEntries.add(SummaryInformation.DEFAULT_STREAM_NAME);
        }
    }
    DocumentSummaryInformation dsi = getDocumentSummaryInformation();
    if (dsi != null) {
        writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, fs);
        if(writtenEntries != null) {
            writtenEntries.add(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
        }
    }

    if (!encryptProps) {
        return;
    }

    // create empty document summary
    dsi = PropertySetFactory.newDocumentSummaryInformation();
    writePropertySet(DocumentSummaryInformation.DEFAULT_STREAM_NAME, dsi, outFS);
    // remove summary, if previously available
    if (outFS.getRoot().hasEntry(SummaryInformation.DEFAULT_STREAM_NAME)) {
        outFS.getRoot().getEntry(SummaryInformation.DEFAULT_STREAM_NAME).delete();
    }
    Encryptor encGen = ei.getEncryptor();
    if (!(encGen instanceof CryptoAPIEncryptor)) {
        throw new EncryptedDocumentException("Using "+ei.getEncryptionMode()+" encryption. Only CryptoAPI encryption supports encrypted property sets!");
    }
    CryptoAPIEncryptor enc = (CryptoAPIEncryptor)encGen;
    try {
        enc.setSummaryEntries(outFS.getRoot(), getEncryptedPropertyStreamName(), fs);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    } finally {
        fs.close();
    }
}
 
Example 23
Source Project: lams   Source File: POIDocument.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return the encryption info if the document is encrypted, otherwise {@code null}
 */
public EncryptionInfo getEncryptionInfo() throws IOException {
    return null;
}
 
Example 24
Source Project: lams   Source File: HSSFWorkbook.java    License: GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("resource")
protected void encryptBytes(byte buf[]) {
    EncryptionInfo ei = getEncryptionInfo();
    if (ei == null) {
        return;
    }
    Encryptor enc = ei.getEncryptor();
    int initialOffset = 0;
    LittleEndianByteArrayInputStream plain = new LittleEndianByteArrayInputStream(buf, 0); // NOSONAR
    LittleEndianByteArrayOutputStream leos = new LittleEndianByteArrayOutputStream(buf, 0); // NOSONAR
    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);
    }
}
 
Example 25
Source Project: lams   Source File: HSSFWorkbook.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public EncryptionInfo getEncryptionInfo() {
    FilePassRecord fpr = (FilePassRecord)workbook.findFirstRecordBySid(FilePassRecord.sid);
    return (fpr != null) ? fpr.getEncryptionInfo() : null;
}
 
Example 26
Source Project: lams   Source File: FilePassRecord.java    License: GNU General Public License v2.0 4 votes vote down vote up
public FilePassRecord(EncryptionMode encryptionMode) {
    encryptionType = (encryptionMode == EncryptionMode.xor) ? ENCRYPTION_XOR : ENCRYPTION_OTHER;
    encryptionInfo = new EncryptionInfo(encryptionMode);
}
 
Example 27
Source Project: lams   Source File: FilePassRecord.java    License: GNU General Public License v2.0 4 votes vote down vote up
public EncryptionInfo getEncryptionInfo() {
    return encryptionInfo;
}
 
Example 28
Source Project: hadoopoffice   Source File: MSExcelWriter.java    License: Apache License 2.0 4 votes vote down vote up
private void finalizeWriteEncryptedXSSF() throws IOException{
	if (this.encryptAlgorithmCipher==null) {
		LOG.error("No encryption algorithm specified");
		return;
	} else
	if (this.hashAlgorithmCipher==null) {
		LOG.error("No hash algorithm specified");
		return;
	} else
	if (this.encryptionModeCipher==null) {
		LOG.error("No encryption mode specified");
		return;
	} else
	if (this.chainModeCipher==null) {
		LOG.error("No chain mode specified");
		return;
	} 
		OutputStream os = null;
		try {
			EncryptionInfo info = new EncryptionInfo(this.encryptionModeCipher, this.encryptAlgorithmCipher, this.hashAlgorithmCipher, -1, -1, this.chainModeCipher);
			Encryptor enc = info.getEncryptor();
			enc.confirmPassword(this.howc.getPassword());
			
			try {
				os = enc.getDataStream(ooxmlDocumentFileSystem);
				if (os!=null) {
					this.currentWorkbook.write(os);
				}
				if (os!=null) {
					os.close();
				}
			} catch (GeneralSecurityException e) {
				LOG.error(e);
			} 

			OutputStream theOS=this.oStream;
			if (this.signUtil!=null) {
				theOS= this.signUtil.getTempOutputStream();
				
			} 
			ooxmlDocumentFileSystem.writeFilesystem(theOS);
			
		} finally {
			
		 if ((this.oStream!=null) && (this.signUtil==null)) { // if we need to sign it we close it later after signing
			 this.oStream.close();
		 }
		}
}