· 9 years ago · Oct 04, 2016, 05:26 PM
1package EorD;
2
3import java.util.Scanner;
4import java.util.Random;
5
6public class encryptDecrypt
7{
8public static char crypt(char input, int random, boolean encrypt)
9{
10 assert random > 0 && random <= 95 : "Valid random number is in range 1 - 95";
11
12 int character = (int) input;
13
14 if (input < 32 || input > 127) {
15 return input;
16 }
17
18 int value = (encrypt) ? (character - 32 + random + 96) : (character - 32 - random + 96);
19
20 return (char)(value % 96 + 32);
21}
22
23public static void encrypt()
24{
25 Scanner scanner = new Scanner(System.in);
26 System.out.println("What sentence would you like to encrypt?");
27 String sentence = scanner.nextLine();
28 char[] secretMessage;
29 secretMessage = sentence.toCharArray();
30 char[] code = new char[sentence.length()];
31 int[] key = new int[sentence.length()];
32 for (int i = 0; i < sentence.length(); i++)
33 {
34
35 int keyCode = generator.nextInt(96);
36 key[i] = keyCode;
37 char encryption = crypt((char)secretMessage[i], keyCode, true);
38 code[i] = encryption;
39 }
40 hiddenMessage = code;
41 secretKey = key;
42 String codes = new String(code);
43 System.out.println("the code is: " + codes);
44 System.out.println();
45 scanner.close();
46}
47public static void decrypt()
48{
49 System.out.println("what message would you like to decrypt?");
50 Scanner scanner = new Scanner(System.in);
51 String sentence = scanner.nextLine();
52 hiddenMessage = sentence.toCharArray();
53 char[] message = new char[sentence.length()];
54 int[] key = new int[sentence.length()];
55 for (int i=0; i< sentence.length(); i++)
56 {
57 int keyCode = generator.nextInt(96);
58 key[i] = keyCode;
59 char decryption = crypt(hiddenMessage[i], key[i], false);
60 message[i] = decryption;
61 }
62 System.out.print("Your secret message was: ");
63 System.out.println(message);
64 scanner.close();
65}
66
67public static void main(String args[])
68{
69 Scanner scanner = new Scanner(System.in);
70 System.out.println("Would you like to encrypt or decrypt?");
71 String sentence = scanner.nextLine();
72 if(sentence.matches("encrypt"))
73 {
74 encrypt();
75 }
76 else if(sentence.matches("decrypt"))
77 {
78 decrypt();
79 }
80 else
81 {
82 System.out.println("This is not a valid option");
83 }
84 scanner.close();
85}
86
87static Random generator=new Random(4711);
88static int[] secretKey;
89static char[] hiddenMessage;
90}