import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SendStream {
public static void main(String[] args) {
String data = "This have I thought good to deliver thee rrrr";
//---------------Encryption ---------------------------------
SecretKey key = null;
try {
KeyGenerator keygen = KeyGenerator.getInstance("DES");
key = keygen.generateKey();
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
FileOutputStream fos = new FileOutputStream("cipher.file");
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
ObjectOutputStream oos = new ObjectOutputStream(cos);
oos.writeObject(data);
oos.flush();
oos.close();
FileOutputStream fosKey = new FileOutputStream("key.file");
ObjectOutputStream oosKey = new ObjectOutputStream(fosKey);
oosKey.writeObject(key);
oosKey.writeObject(cipher.getIV());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ReceiveStream.java
package ucsc.cipher;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class RecieveStream {
public static void main(String[] args) {
SecretKey key = null;
try {
FileInputStream fisKey = new FileInputStream("key.file");
ObjectInputStream oosKey = new ObjectInputStream(fisKey);
key = (SecretKey)oosKey.readObject();
byte[] iv = (byte[])oosKey.readObject();
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
FileInputStream fis = new FileInputStream("cipher.file");
CipherInputStream cis = new CipherInputStream(fis, cipher);
ObjectInputStream ois = new ObjectInputStream(cis);
System.out.println((String)ois.readObject());
} catch (Exception e) {
e.printStackTrace();
}
}
}
