package com.tom.ant;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.*;

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

public class Crypto extends Task {
  	private String keyFile;
  	private String inputFile;
  	private String outputFile;
  	private boolean encrypt = true;
  	private String cypherType = "DES/ECB/PKCS5Padding";

  	public void execute() throws BuildException {
  		Key key;
	   	try {
	   		ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFile));
	    	key = (Key)in.readObject();
	    	in.close();
	    } catch (Exception e) {
	    	throw new BuildException("Unable to find key", e);
	    }

	    Cipher cipher = null;
	    try {
		    cipher = Cipher.getInstance(cypherType);

		    if (encrypt)
		    	cipher.init(Cipher.ENCRYPT_MODE, key);
		    else
		    	cipher.init(Cipher.DECRYPT_MODE, key);
		} catch (Exception e) {
			throw new BuildException("Problem with cipher", e);
		}

		try {
		    FileInputStream in = new FileInputStream(inputFile);
		    FileOutputStream fileout = new FileOutputStream(outputFile);
		    CipherOutputStream out = new CipherOutputStream(fileout, cipher);
		    byte[] buffer = new byte[8192];
		    int length;
		    while ((length = in.read(buffer)) != -1)
		    	out.write(buffer,0,length);
		    in.close();
		    out.close();
		} catch (Exception e) {
			throw new BuildException("I/O Problems", e);
		}
  	}

  	public void setKeyFile(String keyFile) {
    	this.keyFile = keyFile;
  	}

  	public void setInputFile(String inputFile) {
    	this.inputFile = inputFile;
  	}

  	public void setOutputFile(String outputFile) {
    	this.outputFile = outputFile;
  	}

	public void setEncrypt(String encrypt) {
        this.encrypt = Project.toBoolean(encrypt);
    }

  	public void setCypherType(String cypherType) {
    	this.cypherType = cypherType;
  	}

}