/*
 * @(#)encrypt.java	1.1 97/05/02 
 *
 * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

import java.io.*;
import java.security.*;

/**
 * Encrypt the file named by "clear.txt" and store the results
 * in a file named "secret.txt."   Create a DES key to do the encryption,
 * and store that key in a file named "keyfile."    This is only a demo
 * program and should not be confused with a real encryption program :-) !
 * This is a companion demo program to the decrypt.java program. 
 * 
 * @author Marianne Mueller, Vijay Srinivasan
 */

class encrypt {
    public static void main(String args[]) {

	KeyGenerator keyGen;
	Key desKey;
	ObjectOutputStream keyfile;

	SecureRandom rand;

	Cipher cipher;
	CipherOutputStream cos;

	FileInputStream fis;
	FileOutputStream fos;

	byte[] in = new byte[5000];
	int length; 

	try { 

	    // Generate a DES key, and store it in a file named "keyfile"

	    keyGen = KeyGenerator.getInstance("DES");
	    rand = new SecureRandom();
	    keyGen.initialize(rand);
	    desKey = keyGen.generateKey();
	    keyfile = new ObjectOutputStream(new FileOutputStream("keyfile"));
	    keyfile.writeObject(desKey);

	    // Initialize a cipher object for DES

	    cipher = Cipher.getInstance("DES/ECB/PKCS#5");
	    cipher.initEncrypt(desKey);

	    // The file "clear.txt" already exists.   We'll read it in,
	    // and encrypt it using the above DES key, and then store
	    // it to a file named "secret.txt"

	    fis = new FileInputStream("clear.txt");
	    fos = new FileOutputStream("secret.txt");

	    cos = new CipherOutputStream(fos, cipher);
	    length = fis.read(in);
	    cos.write(in, 0, length);
	    fis.close();
	    cos.close();

	} catch (Exception e) {
	    e.printStackTrace();
	}
    }
}



