So I have this as my main program and i also have a util program. when i use the program with a text file it will only rename it but i dont think its encrypting my file contents. When I tested it out it would rename the file and print out the new context but when i used decode in the parameters it wouldnt decrypt the new message am i doing something wrong?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class Prog4 {
public static void main(String[] args){
if (args.length != 3){
System.out.println("Enter the right amount of arguments!");
System.exit(0);
}
String command=args[0];
String key= args[1];
String fileName = args[2];
File file = new File(args[2]);
String fileExtention="";
if(args[0].equals("encode")){
fileExtention=".crypt";
}
else if (args[0].equals("decode")){
fileExtention=".decrypt";
}
else{
System.out.println("Enter decode or encode!");
Syst`enter code here`em.exit(0);
}
File newName = new File(fileName.substring(0,args[2].lastIndexOf("."))+fileExtention);
try{
Scanner sc= new Scanner(file);
PrintWriter out = new PrintWriter(newName);
if(args[0].equals("encode")){
while (sc.hasNextLine()){
Util4.encrypt(sc, out, key);
}
}
else if (args[0].equals("decode")){
while (sc.hasNextLine()){
Util4.decrypt(sc, out, key);
}
}
while (sc.hasNextLine()){
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
} and this is my util
import java.io.PrintWriter;
import java.util.Scanner;
public class Util4 {
public static final int NUM_LETTERS = 26;
public static void encrypt(Scanner sc, PrintWriter out, String key){
while(sc.hasNext()){
char c;
int k;
String temporary="";
String line = sc.nextLine();
for (int i= 0; i< line.length(); ++i){
temporary += shiftUpByK(c= line.charAt(i),k=key.charAt(i%key.length())-'a');
}
System.out.println(temporary);
temporary="";
}
}
public static void decrypt(Scanner sc, PrintWriter out, String key){
while(sc.hasNext()){
char c;
int k;
String temporary="";
String line = sc.nextLine();
for(int i = 0; i < line.length(); ++i){
temporary += shiftDownByK(c=line.charAt(i), k=key.charAt(i%key.length())-'a');
}
System.out.println(temporary);
System.out.flush();
temporary="";
}
}
// shifting up for the encoding process
public static char shiftUpByK(char c, int k) {
if ('a' <= c && c <= 'z')
return (char) ('a' + (c-'a' + k) % NUM_LETTERS);
if ('A' <= c && c <= 'Z')
return (char) ('A' + (c-'A' +k) % NUM_LETTERS);
return c; // don't encrypt if not an alphabetic character
}
// shifting down for the decoding process
public static char shiftDownByK(char c, int k) {
return shiftUpByK(c, NUM_LETTERS-k);
}
}
Aucun commentaire:
Enregistrer un commentaire