Thursday, November 29, 2007

copying files from one FTP Server to another

import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.ProtocolCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;

public class FTP {
Logger logger = Logger.getLogger(FTP .class);
private static String ftpHost="HOST_SOURCE";
private static String userName_sou="username_source";
private static String password_sou="password_source";
private static String directoryLocation_sou="/directoryname";
private static String ftpHost_dest="HOST_DEST";
private static String userName_dest="username_dest";
private static String password_dest="password_dest";
private static String directoryLocation_dest="/directoryname";
public static void main(String[] arg)
{
new FTPClientTest().getFileFromServerLocation();
}
public boolean getFileFromServerLocation()
{
FTPClient client_sou = new FTPClient();
FTPClient client_dest = new FTPClient();
boolean status = false;
boolean connected = false;
ProtocolCommandListener listner=new FrpClientListener();
try
{
// client_sou.addProtocolCommandListener(listner);
// client_dest.addProtocolCommandListener(listner);
//destination directory - start
InetAddress address_dest = InetAddress.getByName(ftpHost_dest);
logger.debug("Connecting to ftp server using " + ftpHost_dest);
// Connect to the host..
client_dest.connect(address_dest);
connected = true;
logger.debug("Loggin on to server using user '" + userName_dest
+ "' and password *********");
if (this.password_dest == null)
{
}
boolean flag_dest = client_dest.login(this.userName_dest, this.password_dest);
logger.debug("Log on status " + flag_dest);
logger.debug("Reply String: " + client_dest.getReplyString());
logger.debug("Working dir:" + client_dest.printWorkingDirectory());
// get the current working dir.
String workingDir_dest = client_dest.printWorkingDirectory();
String currworkingDir_dest = client_dest.printWorkingDirectory()+directoryLocation_dest;
boolean workingDirStatus_dest = client_dest.changeWorkingDirectory(workingDir_dest
+ directoryLocation_dest);
//destination directory - end
// source directory - start
InetAddress address_sou = InetAddress.getByName(ftpHost);
logger.debug("Connecting to ftp server using " + ftpHost);
// Connect to the host..
client_sou.connect(address_sou);
connected = true;
logger.debug("Loggin on to server using user '" + userName_sou
+ "' and password *********");
if (this.password_sou == null)
{
}
boolean flag = client_sou.login(this.userName_sou, this.password_sou);
logger.debug("Log on status " + flag);
logger.debug("Reply String: " + client_sou.getReplyString());
logger.debug("Working dir:" + client_sou.printWorkingDirectory());
// get the current working dir.
String workingDir_sou = client_sou.printWorkingDirectory();
String currworkingDir = client_sou.printWorkingDirectory()+directoryLocation_sou;
// change the current working dir to the specified dir..
boolean workingDirStatus = client_sou.changeWorkingDirectory(workingDir_sou
+ directoryLocation_sou);
if (!workingDirStatus)
{
}
logger.debug("Current working dir:"
+ client_sou.printWorkingDirectory());
// source directory - end
this.logger.debug("Uploading file to server......");
String file="";
FTPFile[] files = client_sou.listFiles();
for (int i = 0; i < files.length; i++)
{
FTPFile f = files[i];
file = f.getName();
client_dest.enterRemotePassiveMode();
client_sou.enterRemoteActiveMode(InetAddress.getByName(client_dest.getPassiveHost()),
client_dest.getPassivePort());
if (client_sou.remoteRetrieve(file) && client_dest.remoteStore(file))
{
// if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) {
// We have to fetch the positive completion reply.
client_sou.completePendingCommand();
client_dest.completePendingCommand();
}

}
logger.debug("File transfer status " + flag);
client_sou.sendNoOp();
status = true;
}
catch (UnknownHostException une)
{
une.printStackTrace();
}
catch (SocketException se)
{
se.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch (Throwable e)
{
e.printStackTrace();
}
finally
{
try
{
if (connected)
{
this.logger
.debug("Logout ftp connection and disconnecting..");
client_sou.logout();
client_sou.disconnect();
client_dest.logout();
client_dest.disconnect();
this.logger.debug("Logout successful.");
}
}
catch (IOException e)
{
this.logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
return status;
}
}

Eccyption ad decryption

For encryption and decryption of Strings(loke password or a credit card number) use:


import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;

public class DesEncrypt {
Cipher ecipher;
Cipher dcipher;
DesEncrypt(SecretKey key) {
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
System.err.println("input : "+ str);
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
System.out.println("encryption success");
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
}


call this class using the following code snippet :


try {
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
System.err.println("key value : "+ key);
// Create encrypter/decrypter class
DesEncrypt encrypter = new DesEncrypt(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
System.err.println("encrypted value : "+ encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.err.println("decrypted value : "+ decrypted);
} catch (Exception e) {
}

}



If you need to encrypt or decrypt a file, use the following :
NB: To run this Java class you would need three text files namely test.txt(which will contain the key or password as you may call it.This key will be read and verified everytime you try to encrypt or decrypt), read_file.txt(which will contain the input text that needs to be encrypted) and an write_file.txt(which will contain the encrypted text and later gets decrypted).
Other than that,I have hardcoded the argument for generation of a key,encryption or decryption (-g,-e and -d respectively).You would need to change the value accordingly, and in the sameorder at the line args[0] = "-d";

import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;
import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;
import java.io.OutputStream;import java.io.PrintStream;
import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;
import java.security.Provider;import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;import javax.crypto.IllegalBlockSizeException;import javax.crypto.KeyGenerator;import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

/**
* This class defines methods for encrypting and decrypting using the Triple DES * algorithm and for generating, reading and writing Triple DES keys. It also * defines a main() method that allows these methods to be used from the command * line.
*/

public class TripleDES {
/**
* The program. The first argument must be -e, -d, or -g to encrypt, * decrypt, or generate a key. The second argument is the name of a file * from which the key is read or to which it is written for -g. The -e and * -d arguments cause the program to read from standard input and encrypt or * decrypt to standard output.
*/

public static void main(String[] args) {
try {
args = new String[2];
args[0] = "-e";
args[1] = "D:/encryption_test/test.txt";
String var = "xxxxxxxx";

File keyfile = new File(args[1]);
FileInputStream is = new FileInputStream("D:/encryption_test/read_file.txt");
// Now check the first arg to see what we're going to do
if (args[0].equals("-g")) {
// Generate a key
System.out.print("Generating key. This may take some time...");
System.out.flush();
SecretKey key = generateKey();
writeKey(key, keyfile);
System.out.println("done.");
System.out.println("Secret key written to " + args[1] + ". Protect that file carefully!");
} else if (args[0].equals("-e")) {
// Encrypt stdin to stdout
SecretKey key = readKey(keyfile);
OutputStream os=new FileOutputStream("D:/encryption_test/write_file.txt");
encrypt(key, is, os);
} else if (args[0].equals("-d")) {
// Decrypt stdin to stdout
SecretKey key = readKey(keyfile);
FileInputStream isdec = new FileInputStream("D:/encryption_test/write_file.txt"); decrypt(key, isdec, System.out);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(e);
System.err.println("Usage: java " + TripleDES.class.getName() + " -d-e-g ");
}
}
/** Generate a secret TripleDES encryption/decryption key */

public static SecretKey generateKey() throws NoSuchAlgorithmException {
// Get a key generator for Triple DES (a.k.a DESede)
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
// Use it to generate a key
return keygen.generateKey(); }
/** Save the specified TripleDES SecretKey to the specified file */
public static void writeKey(SecretKey key, File f) throws IOException,NoSuchAlgorithmException, InvalidKeySpecException {
// Convert the secret key to an array of bytes like this
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key, DESedeKeySpec.class);
byte[] rawkey = keyspec.getKey();
// Write the raw key to the file
FileOutputStream out = new FileOutputStream(f); out.write(rawkey); out.close(); }
/** Read a TripleDES secret key from the specified file */
public static SecretKey readKey(File f) throws IOException,NoSuchAlgorithmException, InvalidKeyException,InvalidKeySpecException {
// Read the raw bytes from the keyfile
DataInputStream in = new DataInputStream(new FileInputStream(f));
byte[] rawkey = new byte[(int) f.length()];
in.readFully(rawkey);
in.close();
// Convert the raw bytes to a secret key like this
DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyfactory.generateSecret(keyspec);
System.out.println("key treading successful"+ key);
return key; }
/**
* Use the specified TripleDES key to encrypt bytes from the input stream * and write them to the output stream. This method uses CipherOutputStream * to perform the encryption and write bytes at the same time.
*/
public static void encrypt(SecretKey key, InputStream in, OutputStream out) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException {
// Create and initialize the encryption engine
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Create a special output stream to do the work for us
CipherOutputStream cos = new CipherOutputStream(out, cipher);
System.out.println("encrypting....");
// Read from the input and write to the encrypting output stream
byte[] buffer = new byte[2048];
int bytesRead;
bytesRead = in.read(buffer);
if (bytesRead!= -1) {
cos.write(buffer, 0, bytesRead);
}
System.out.println("encrypting successful");
cos.close();
// For extra security, don't leave any plaintext hanging around memory. java.util.Arrays.fill(buffer, (byte) 0);
}
/**
* Use the specified TripleDES key to decrypt bytes ready from the input * stream and write them to the output stream. This method uses uses Cipher * directly to show how it can be done without CipherInputStream and * CipherOutputStream.
*/

public static void decrypt(SecretKey key, InputStream in, OutputStream out) throws NoSuchAlgorithmException, InvalidKeyException, IOException,IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException
{
// Create and initialize the decryption engine
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
// Read bytes, decrypt, and write them out.
byte[] buffer = new byte[2048]; int bytesRead;
bytesRead = in.read(buffer);
if (bytesRead != -1) {
out.write(cipher.update(buffer, 0, bytesRead));
}
// Write out the final bunch of decrypted bytes
out.write(cipher.doFinal());
out.flush();
}
}

REFACTORING

 What is Refactoring? A software is built initially to serve a purpose, or address a need. But there is always a need for enhancement, fixin...