· 7 years ago · Aug 01, 2018, 08:22 PM
1package encryption;
2
3import java.io.*;
4import java.net.*;
5import java.security.*;
6import javax.crypto.*;
7
8public class CipherClient
9{
10 public static void main(String[] args) throws Exception,NoSuchAlgorithmException,
11 NoSuchPaddingException,
12 BadPaddingException,
13 IllegalBlockSizeException,
14 InvalidKeyException
15 {
16 String message = "The quick brown fox jumps over the lazy dog.";
17 String host = "localhost";
18 int port = 9999;
19 Socket s = new Socket(host, port);
20
21 // declare cipher variable
22 Cipher desCipher;
23
24 // generate key
25 KeyGenerator keygen = KeyGenerator.getInstance("DES");
26 SecretKey desKey = keygen.generateKey();
27
28 // create file / place key in file
29
30 File keyFile = new File("Keyfile.txt");
31 ObjectOutputStream fileTxt = new ObjectOutputStream(new FileOutputStream(keyFile));
32
33 fileTxt.writeObject(desKey);
34
35 // send key file
36
37 ObjectOutputStream fileSocket = new ObjectOutputStream(s.getOutputStream());
38 fileSocket.writeObject(desKey);
39 fileSocket.flush();
40
41 // create cipher, initialize for encryption
42 desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
43 desCipher.init(Cipher.ENCRYPT_MODE,desKey);
44
45 // cleartext
46 //byte[] cleartext = message.getBytes();
47 byte cleartext[] = message.getBytes();
48
49 // encrypt cleartext
50 //byte[] ciphertext = desCipher.doFinal(cleartext);
51 byte ciphertext[] = desCipher.doFinal(cleartext);
52
53 // send object
54 CipherOutputStream cipherOutput = new CipherOutputStream(s.getOutputStream(),desCipher);
55
56 cipherOutput.write(ciphertext);
57
58 // show cleartext and ciphertext
59 System.out.println(
60 "The cleartext is: "+message
61 +
62 "The ciphertext is: "+ciphertext+"."
63 );
64
65 //Close all open resources
66 fileTxt.close();
67 cipherOutput.close();
68 s.close();
69 fileSocket.close();
70
71
72
73 /*
74 Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
75 desCipher.init(Cipher.ENCRYPT_MODE, desKey);
76 */
77
78 //byte[] encryptedMessage = desCipher.doFinal(message);
79 //System.out.println(new String(encryptedMessage));
80
81
82
83
84 // YOU NEED TO DO THESE STEPS:
85 // -Generate a DES key.
86 // -Store it in a file.
87 // -Use the key to encrypt the message above and send it over socket s to the server.
88 }
89
90}