Von C nach Java, Teil 4: Datenkompression und Verschlüsselung

Seite 12: Listing 8

Inhaltsverzeichnis
package net.nieden.FileCrypter;

import java.io.*;
import java.util.*;
import javax.crypto.*;

public class CFileEncrypter implements IFileProcessInterrupter {
private int blocks2Go, bufSizeKB;
private IFileProgressIndicator pgrsIndicator=null;
private File iFile;
private boolean compression=false, multiThreaded=false,
storePasswd=false, is7zip=false;
Boolean canceled=false;
private String passwd;
private Cipher ecipher;

public CFileEncrypter(File f, int bufSizeKB, String passwd)
throws Exception {
this.bufSizeKB=bufSizeKB;
this.passwd=passwd;
this.multiThreaded=false;
blocks2Go=(int)f.length()/(bufSizeKB*1024);
if (f.length()%((bufSizeKB*1024))>0) blocks2Go++;
this.iFile=f;
ecipher=CFileTools.initEncryption(passwd);
}

public void processFile() throws Exception {
if (canceled) return;
String fileOutputName;
CFileBlockProcessor blockProc=null;
FileInputStream fis=new FileInputStream(iFile);
FileOutputStream fos=new FileOutputStream
((fileOutputName=String.format("ENCRY_%012x.bin",
new Date().getTime())));
CFileHeader hdr=new CFileHeader(bufSizeKB, compression,
iFile, ecipher, (storePasswd)?passwd:null);
hdr.writeHdr(fos);
if (multiThreaded)
blockProc=new CFileBlockProcessor(blocks2Go,
true, pgrsIndicator);
for (int i=0;i<blocks2Go;i++) {
byte[] iBuffer=CFileTools.readFromInputStream(fis,
bufSizeKB*1024);
if (iBuffer==null) break;
if (multiThreaded) {
for (;;) {
// wait for free thread ...
if (canceled) break;
int count=blockProc.getWorkingThreadCount();
if (count < blockProc.maxThreads) {
blockProc.blockProcThreadList.get(i)
.startWorking(iBuffer, compression,
is7zip,passwd, fos);
break;
}
Thread.sleep(100);
}
} else {
if (canceled) break;
if (compression) iBuffer=CFileTools.compressBlock
(iBuffer, is7zip);
byte[] oBuffer=CFileTools.encryptBlock(ecipher, iBuffer);
CFileTools.writeLengthToFile(oBuffer.length, fos);
fos.write(oBuffer, 0, oBuffer.length);
if (canceled) break;
if (pgrsIndicator != null) {
if (!pgrsIndicator.progressIndicator(i, blocks2Go))
break;
}
}
if (canceled) break;
}
fis.close();
if (!canceled && multiThreaded) {
// wait for last block to finish
blockProc.waitForLastBlock();
}
fos.close();
if (canceled) {
new File(fileOutputName).delete();
}
}

public void interrupt() {
synchronized (canceled) {
canceled=true;
}
}

public int getNumberOfBlocksToProcess() {
return blocks2Go;
}

public void setCompression(boolean compression) {
setCompression(compression, false);
}

public void setCompression(boolean compression, boolean is7zip) {
this.compression=compression;
this.is7zip=is7zip;
}

public void setMultiThreaded(boolean multiThreaded) {
this.multiThreaded=multiThreaded;
}

public void setStorePasswd(boolean storePasswd) {
this.storePasswd=storePasswd;
}

public void setProgressIndicator(IFileProgressIndicator prgsIndicator) {
this.pgrsIndicator=prgsIndicator;
}
} (ane)