Encryption-Decryption
Description
Modify the previous program to work with command-line arguments instead of the standard input. The program must parse three arguments: -mode, -key and -data. The first argument should determine the program’s mode (enc - encryption, dec - decryption). The second argument is an integer key to modify the message, and the third argument is a text or ciphertext within quotes to encrypt or decrypt.
All the arguments are guaranteed to be passed to the program. If for some reason it turns out to be wrong:
If there is no -mode, the program should work in enc mode. If there is no -key, the program should consider that key = 0. If there is no -data, the program should assume that the data is an empty string. Keep in mind that arguments may be in different order. For example, -mode enc may be at the end, at the beginning or in the middle of arguments array.
Run configuration examples for encryption
java Main -mode enc -key 5 -data "Welcome to hyperskill!"
Encryption output example
\jqhtrj%yt%m~ujwxpnqq&
Run configuration examples for decryption
java Main -key 5 -data "\jqhtrj%yt%m~ujwxpnqq&" -mode dec
Decryption output example
Welcome to hyperskill!
You still need to submit a correct solution for this stage to proceed further with the project. Write a program
solution1:
package encryptdecrypt;
public class Main {
public static void main(String[] args) {
String mode = "enc";
int key = 0;
String data = "";
for (int i = 0; i < args.length; i += 2) {
if (args[i].equals("-mode")) {
mode = args[i+1];
} else if (args[i].equals("-key")) {
key = Integer.parseInt(args[i+1]);
} else if (args[i].equals("-data")) {
data = args[i+1];
}
}
switch (mode) {
case "enc":
getEncryption(data, key);
break;
case "dec":
getDecryption(data, key);
break;
}
}
public static void getDecryption(String data, int key) {
for (char item : data.toCharArray()) {
char shiftItem = (char) (item - key);
System.out.print(shiftItem);
}
}
public static void getEncryption(String data, int key) {
for (char item : data.toCharArray()) {
char shiftItem = (char) (item + key);
System.out.print(shiftItem);
}
}
}
solution2:
package encryptdecrypt;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("-mode", "enc");
map.put("-key", "0");
map.put("-data", "");
for (int i=0; i < args.length; i+=2) {
map.put(args[i], args[i+1]);
}
final String data = map.get("-data");
final String mode = map.get("-mode");
final int key = Integer.parseInt(map.get("-key"));
for (int i=0; i < data.length(); i++) {
System.out.print((char)("enc".equals(mode) ? data.charAt(i) + key : data.charAt(i) - key));
}
}
}