import java.io.*; import java.net.*; import java.security.*; import javax.crypto.*; public class CipherClient { public static void main(String[] args) throws Exception { // -Generate a DES key. Key key1; KeyGenerator kg = KeyGenerator.getInstance("DES"); kg.init(new SecureRandom()); key1 = kg.generateKey(); String message = "The quick brown fox jumps over the lazy dog."; String host = "127.0.0.1"; int port = 7999; Socket s = new Socket(host, port); // -Store it in a file. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Keyfile3.txt")); out.writeObject(key1); out.close(); // -Use the key to encrypt the message above and send it over socket s to the server. Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key1); CipherOutputStream cipherout = new CipherOutputStream(s.getOutputStream(),cipher); cipherout.write(message.getBytes()); } }import java.io.*; import java.net.*; import java.security.*; import javax.crypto.*; public class CipherServer { public static void main(String[] args) throws Exception { int port = 7999; ServerSocket server = new ServerSocket(port); Socket s = server.accept(); // -Read the key from the file generated by the client. ObjectInputStream in = new ObjectInputStream(new FileInputStream("Keyfile3.txt")); Key key1 = (Key)in.readObject(); // -Use the key to decrypt the incoming message from socket s. Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key1); CipherInputStream cipherIn = new CipherInputStream(s.getInputStream(), cipher); // -Print out the decrypt String to see if it matches the original message. FileOutputStream fos = new FileOutputStream("output3.txt"); byte[] buffer = new byte[1024]; int length = cipherIn.read(buffer); fos.write(buffer, 0, length); fos.flush(); fos.close(); cipherIn.close(); } }
Errors that I'm getting on CipherClient:
run:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.pee kByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputS tream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputSt ream.java:369)
at CipherServer.main(CipherServer.java:16)
Java Result: 1
BUILD SUCCESSFUL (total time: 8 seconds)
Errors that I get when running on CipherServer:
run:
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutp utStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStre am.java:141)
at javax.crypto.CipherOutputStream.write(CipherOutput Stream.java:157)
at javax.crypto.CipherOutputStream.write(CipherOutput Stream.java:141)
at CipherClient.main(CipherClient.java:30)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)