· 6 years ago · Mar 02, 2019, 11:16 PM
1package exercise1;
2
3import java.util.Arrays;
4import java.util.Scanner;
5import javax.crypto.Cipher;
6import javax.crypto.KeyGenerator;
7import javax.crypto.SecretKey;
8
9/**
10 *
11 * @author Lester
12 */
13public class des_encryption {
14
15 public static void main(String[] args) throws Exception {
16 Scanner in = new Scanner(System.in);
17 System.out.println("Hello User! ");
18 System.out.println("Please enter message 'No body can see me' to test out the DES Algorithm");
19 String UserInput = in.nextLine();
20 while (!"No body can see me".equals(UserInput)) {
21 System.out.println("Wrong text, enter the following text: No body can see me");
22 UserInput = in.nextLine();
23 }
24
25 SecretKey Destination_Key = desKeyGen();
26 byte[] encryptedMessage = desEncrypt(UserInput, Destination_Key);
27
28 System.out.println("The encrypted message is: ");
29 System.out.println(Arrays.toString(encryptedMessage));
30
31 String decryptedMessage = desDecrypt(encryptedMessage, Destination_Key);
32
33 System.out.println("The decrypted message is: ");
34 System.out.println(decryptedMessage);
35
36 in.close();
37 }
38
39 public static SecretKey desKeyGen() throws Exception {
40 KeyGenerator Keys = KeyGenerator.getInstance("DES");
41 SecretKey Destination_Key = Keys.generateKey();
42
43 return Destination_Key;
44 }
45
46 public static byte[] desEncrypt(String message, SecretKey Destination_Key) {
47 try {
48 byte[] byteMessage = message.getBytes("UTF8");
49
50 Cipher cipherDes = Cipher.getInstance("DES");
51 cipherDes.init(Cipher.ENCRYPT_MODE, Destination_Key);
52
53 byte[] encryptedMessage = cipherDes.doFinal(byteMessage);
54
55 return encryptedMessage;
56 } catch (Exception e) {
57 System.out.println(e);
58 return null;
59 }
60 }
61
62 public static String desDecrypt(byte[] encryptedMessage, SecretKey Destination_Key) {
63 try {
64 Cipher cipherDes = Cipher.getInstance("DES");
65 cipherDes.init(Cipher.DECRYPT_MODE, Destination_Key);
66
67 byte[] decryptedMessage = cipherDes.doFinal(encryptedMessage);
68
69 String plaintext = new String(decryptedMessage, "UTF-8");
70
71 return plaintext;
72 } catch (Exception e) {
73 System.out.println(e);
74 return null;
75 }
76
77 }
78
79}