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

The following examples show how to use org.apache.poi.poifs.crypt.EncryptionInfo. 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 File: Poi3Test.java    From easyexcel with 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 #2
Source File: WriteContextImpl.java    From easyexcel with 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 #3
Source File: BinaryRC4Encryptor.java    From lams with 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 File: RecordFactoryInputStream.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #5
Source File: FilePassRecord.java    From lams with 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 #6
Source File: StandardEncryptor.java    From lams with 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 #7
Source File: CryptoAPIEncryptor.java    From lams with 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 #8
Source File: CryptoAPIDecryptor.java    From lams with 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 #9
Source File: MSExcelOOXMLSignUtil.java    From hadoopoffice with 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 #10
Source File: FileExportUtil.java    From myexcel with 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 #11
Source File: AttachmentExportUtil.java    From myexcel with 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 #12
Source File: RecordInputStream.java    From lams with 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 #13
Source File: HSSFWorkbook.java    From lams with 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 #14
Source File: CryptoAPIDecryptor.java    From lams with 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 File: CryptoAPIEncryptor.java    From lams with 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 #16
Source File: StandardEncryptionInfoBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: XOREncryptionInfoBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #18
Source File: XOREncryptionInfoBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #19
Source File: DocumentFactoryHelper.java    From lams with 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 #20
Source File: POIDocument.java    From lams with 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 #21
Source File: POIDocument.java    From lams with 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 #22
Source File: HSSFWorkbook.java    From lams with 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 #23
Source File: HSSFWorkbook.java    From lams with 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 #24
Source File: FilePassRecord.java    From lams with 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 #25
Source File: StandardEncryptionInfoBuilder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 #26
Source File: FilePassRecord.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public EncryptionInfo getEncryptionInfo() {
    return encryptionInfo;
}
 
Example #27
Source File: XORDecryptor.java    From lams with 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 #28
Source File: MSExcelWriter.java    From hadoopoffice with 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();
		 }
		}
}