Password guessing program problems - java

I'm having a few issues with an extra credit assignment for my Java class. The objective is to decrypt a file without the password. It is encrypted with the PBEWithSHA1AndDESede algorithm and the password is a dictionary word with no numbers or special characters.
The way I'm trying to solve this is by guessing the password over and over again until I get it right using the code below.
The problem I'm running into is that the extra_out.txt file is being output after the first cycle of the for loop, when I want it to only be output if the correct word is guessed.
So when it runs, I get the exception "Encryption Error" and then the extra_out.txt file is output (still encrypted) and then 9999 more "Encryption Errors."
Any helpful advice is greatly appreciated!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class WordGuess {
public static void main(String[] args) {
ArrayList<String> words = new ArrayList();
Random numGen = new Random();
String curWord = "";
try {
File aFile = new File("english.txt");
Scanner reader = new Scanner(aFile);
while (reader.hasNext()) {
curWord = reader.next();
if (curWord.length() == 5) {
words.add(curWord);
}
}
}
catch (FileNotFoundException e) {
System.out.println("Error: " + e);
}
for(int i = 0; i < 10000; i++){
int rand = Math.abs(numGen.nextInt(words.size()));
File fileIn = new File("extracredit.enc");
File fileOut = new File("extra_out.txt");
String password = words.get(rand);
crackFile(fileIn, fileOut, password);
}
}
public static void crackFile(File input, File output, String password) {
try{
Crypt c = new Crypt(password);
byte[] bytes = FileIO.read(input);
FileIO.write(output, c.decrypt(bytes));
}
catch (IOException e) {
System.out.println("Could not read/write file");
}
catch (Exception e) {
System.out.println("Encryption error");
}
}
}

Related

The infinite monkey theorem in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:
package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* #author robi1
*/
public class RandomString {
public static void main(String[] args){
List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "final.txt");
String letters = "abcdefghijklmnopqrstuvwxyz ";
Object[] wrds = readFile("basicWordsInEnglish.txt");
int x = wrds.length;
String[] words = new String[x];
for(int i =0;i<x;i++){
words[i] = wrds[i].toString();
}
char[] let = letters.toCharArray();
String n ="";
Random r = new Random();
char t;
}
public static Object[] readFile(String name){
ArrayList<String> al = new ArrayList<String>();
FileInputStream fstream;
try {
fstream = new FileInputStream(name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine=br.readLine())!=null){
if(strLine.length()>4)
al.add(strLine);
}
fstream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object[] array = al.toArray();
return array;
}
public static List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public RandomString(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.
public void main(String... args) {
List<String> dictionary = readDictionaryFrom("path to dictionary");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "path to destination file");
}
public List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10_000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
Use the debugging feature of your favorite IDE (might be Eclipse), set an exception breakpoint on ArrayIndexOutOfBoundsException, run your program in debug mode.
When it hits the exception, Eclipse will halt your program. Look at your variable values, especially which array you are accessing and what value the index has, and why it got a value outside of the array size.
By the way, your code line if(n.length()>4){ cannot produce an ArrayIndexOutOfBoundsException, as there's no array indexing in that line.

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

cannot create a txt file

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
String name = null;
public String nameInitials(String sentence)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new FileOutputStream("abc.txt."));
outputStream.println(sentence);
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("abc.txt."));
}
catch (FileNotFoundException e)
{
System.out.println("File not found.");
System.exit(0);
}
do
{
String word = inputStream.next();
char initial = word.charAt(0);
name = initial+"."+name;
} while (inputStream.hasNext());
return name;
}
public void main(String[]args)
{
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
Write a method called nameInitials that takes one String as argument, pertaining to somebody's full name and returns a String of the name's initials. Usage example,
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials); //should print B.A.W.R.
I try to store the full name to a txt file and read the file. But I don't know why I cannot create the abc.txt file in the folder.
This can fix your error, I tested it
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class Exercise4
{
static String name = null;
public static String nameInitials(String sentence) {
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new FileOutputStream("C:\\temp\\abc.txt"));
outputStream.println(sentence);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
outputStream.close();
Scanner inputStream = null;
try {
inputStream = new Scanner(new FileInputStream("C:\\temp\\abc.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
do {
String word = inputStream.next();
char initial = word.charAt(0);
name = initial + "." + name;
} while (inputStream.hasNext());
return name;
}
public static void main(String[] args) {
String initials = nameInitials("Bertrand Arthur William Russell");
System.out.println(initials);
}
}
the path of file not should end of .txt. just .txt
Your code is perfect it is creating the file "abc.txt." at the project level If you want to create a file named abc.txt then you must change;
new FileOutputStream("abc.txt.") to new FileOutputStream("abc.txt")
and
new FileInputStream("abc.txt.") to new FileInputStream("abc.txt")
And if you want to create the file in a particular directory then provide the full path of that directory with the file name you want to create.
for ubuntu system;
new FileOutputStream("/home/java/abc.txt")
&
new FileInputStream("/home/java/abc.txt")
and for windows system;
new FileOutputStream("C:/java/abc.txt")
&
new FileInputStream("C:/java/abc.txt")

Take numbers from a file and sort them

I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}

Is there a way to make this Java program more interactive?

I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}

Categories

Resources