I am struggling a bit with some loops I put together for an authentication type system. I am trying to get the code to re-prompt the user to quit if they do not enter 'q', it will display the message that they are still logged in but reverts back to the main loop and asks to input the username again. I was playing with continue and break but so far it will not repeat the inner If statement. Any guidance would be much appreciated.
package zooauthfinal;
import java.util.Scanner;
import java.io.File;
import java.security.MessageDigest;
public class ZooAuthFinal {
public static void main (String[] args) throws Exception {
//Creates new scanner for user input
Scanner scan = new Scanner(System.in);
//variable to attempts to track login attempts
int attempts = 0;
//While loop to start collecting user credentials for login
while(true) {
System.out.print("Enter username: ");
String user = scan.nextLine(); //reads user input and assigns to variable "user"
System.out.print("Enter password: ");
String original = scan.nextLine(); //reads user input and assigns to variable "original" for original password
//MD5 conversion script
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
//System.out.println("original:" + original); //Used to check and compare password conversion - shows original user input
//System.out.println("digested:" + sb.toString()); //Used to check and compare password conversion - shows MD5 conversion of original user input
//assigns boolean value to variable "done"
boolean done=false;
//new scanner to read "credentials.txt" file to authenticate user
Scanner file = new Scanner (new File("credentials.txt"));
//While loop to split text file into columns
while(file.hasNextLine ()) {
String record = file.nextLine();
String columns[] = record.split("\t");
//If statement to match value to username
if(columns[0].trim().equals(user)) {
if(columns[1].trim().equals(sb.toString())) {
done=true;
Scanner sc = new Scanner (new File(columns[3].trim() +".txt"));
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
break;
}
}
}
//If statment to start logout procedure, starts when user has been authenticated and user role message has been delivered based on user role
if(done) {
//Instructs user to logout with value 'q'
System.out.println("Type 'q' to logout: ");
String ch = scan.nextLine();
if(ch.toLowerCase().charAt(0) != 'q') {
System.out.println("You are still logged in as " + user +".");
}
//Assigns user input to lowercase value and checks if matches required 'q'
else {
System.out.println("Successfully logged out. Have a nice day!");
}
}
}
//If/else to track number of login attempts (limit 3) and adds 1 to each unsuccessful attempt until 3 attempts, then displays exit protocol
else {
attempts ++;
if(attempts==3) {
System.out.println("Could not verify credentials. Goodbye.\n");
break;
}
//displays login error message on each unsucessful attempt until the third unsuccessful attempt
else {
System.out.println("Invalid username or password, please try again.");
}
}
}
}
Add break statement as last line in if(done) block.
if(!ch.toLowerCase().equals("q"))
Related
Question:
create a class named Account that contains the string fields name, email and
password.
Develop a program called LoginSim that simulates a login procedure.
The program reads a list of names, email addresses and passwords from a file pw.txt.
Store the information in an ArrayList of Account objects.
*Note: for Netbeans users the file must be placed in a test folder and accessed with new File("test/pw.txt");
Your program will prompt the user for their email address.
If the email is not in the system, prompt the user to try again. Give them an option to quit.
If the email is found in the system, prompt the user to enter their password.
After 3
unsuccessful tries, inform the user that they are locked out and end the program.
If the password matches, welcome the user by name and ask if they would like to change their
password.
If so, prompt for the new password and change it accordingly. If not, end the
program by confirming that they have signed out.
When the program ends, display the list of accounts.
Sample output:
Enter your email address (q to quit):
draco#hogwarts.com
Email not found, please try again (q to quit):
dmalfoy#hogwarts.com
Email not found, please try again (q to quit):
q
Goodbye!
pw.txt
Hagrid hagrid#hogwarts.com 111
Harry harry#hogwarts.com killvoldy777
Ron ron#hogwarts.com mypassword123
Hermione hermione#hogwarts.com 98fJG83h*4iwrej!
What should I do next, exception at line 16
import java.util.*;
import java.io.*;
public class LoginSim {
private static int index;
public static void main(String args[]) throws
FileNotFoundException, ArrayIndexOutOfBoundsException {
String em;
String pw;
Scanner f = new Scanner(new File("src/pw.txt"));
Scanner kb = new Scanner(System.in);
String[] email = new String[3];
String[] password = new String[3];
int i = 0;
while (f.hasNext()) {
email[i] = String.valueOf(f.hasNext());
password[i] = String.valueOf(f.hasNext());
i++;
}
System.out.println("Enter Email:");
em = kb.next();
System.out.println("Enter Password:");
pw = kb.next();
if (index != -1) {
System.out.println("Enter pw:");
pw = kb.next();
int tries = 0;
while (!pw.equals(tries < 2) &&
!pw.equals(password[index])) {
System.out.println("Incorrect Password, Try Again");
tries++;
pw = kb.next();
}
if (pw.equals(password[index])) {
System.out.println("Successful Login");
}else {
System.out.println("3 Strikes, Locked out");
}
System.out.println("Email not found");
}
}
}
Ok, you are getting java.lang.ArrayIndexOutOfBoundsException: 3 in this line email[i] = String.valueOf(f.hasNext()); because the size of your array is 3 (String[] email = new String[3];), but you are trying to add more then 3 entries to it, at least 4 based on your sample "pw.txt".
Also, you have the same issue with your password array.
I built a simple java app. However, I can't understand how could I secure this app to avoid hard-coded passwords that a decompiler won't be able to reveal.
LoginMain
import java.util.Scanner;
public class LoginMain {
public static void main(String[] args) {
String Username;
String Password;
Password = "admin";
Username = "admin";
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
LoginNew.java
import java.util.Scanner;
public class LoginNew {
public static void main(String[] args) {
String Username;
String Password;
Scanner scan = new Scanner (new File("1.txt"));
Scanner input1 = new Scanner(System.in);
System.out.println("Enter Username : ");
String username = input1.next();
Scanner input2 = new Scanner(System.in);
System.out.println("Enter Password : ");
String password = input2.next();
if (username.equals(Username) && password.equals(Password)) {
System.out.println("Access Granted! Welcome!");
} else if (username.equals(Username)) {
System.out.println("Invalid Password!");
} else if (password.equals(Password)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Invalid Username & Password!");
}
}
}
However, the system presents me :
loginNew.java:9: error: cannot find symbol
Scanner scan = new Scanner (new File("1.txt"));
^
symbol: class File
location: class loginNew
1 error
Error: Could not find or load main class loginNew
I created the file 1.txt with my credentials: Password = "admin";
Username = "admin"; Simple stuff but Im lost. sorry..
Normally, passwords wouldn't even be stored in the application code - they'd be validated against a database or some other data source. But throwing those concerns aside for a moment...
The answer to your question is to use a one-way hash. That is, encrypt the password with a hash function that can't be reversed. When the user types in a password, hash it and compare it to the hash that's stored in your application code. (Replace the password variable with a passwordHash variable.) Because the hash can't be (easily) decrypted, it's more secure than storing the plain-text password in your application source (or database, or wherever else you may be storing hashed passwords).
As others have alluded to, cryptographic hashing (and application security) can get complex very quickly, and isn't particularly friendly for beginners to work with. So this answer might help you understand some concepts, but you might need a bit more to secure a production-quality application.
I am trying to write a very simple program which captures a few key pieces of info about a prospective job and inserts those into a prepared cover letter. I have imported Java's scanner utility as you can see in my code. When I run it via the "Java" command in windows' cmd prompt, the first System.out.println command appears and I (the user) input as prompted. But then, the console simply outputs exactly what I input and does not move on to other parts of the code. Also, as you can see, the console only outputs the first word of whatever I input.
I am very new at programming, can anyone spot what I must be missing?
I will include an image of the console here (code below):
Link to picture - Lack to reputation needed to edit in photos
find code below
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.next();
reader.close();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.next();
reader.close();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.next();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + "as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}![enter image description here](https://i.stack.imgur.com/EqheW.jpg)
You have two problems you close your scanner too soon and you use next() instead of nextLine(). Don't forget to recompile! I tested those fixes and it works for me. This code:
import java.util.Scanner;
public class CoverLetter {
public static void main(String[] args) {
System.out.println("Welcome to tera_byteme's Simple Cover Letter Generator.");
// defines scanner "reader", prompts user to enter business name, stores that in a string var "bizName", closes reader
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the business name.");
String bizName = reader.nextLine();
//same as above block but asks for position title, stores in string var "posTitle"
System.out.println("Please enter position title.");
String posTitle = reader.nextLine();
//"" but asks for user's name, stores in string var "userName"
System.out.println("Please enter your name.");
String userName = reader.nextLine();
reader.close();
String seg1 = new String();
seg1 = "My name is " + userName + " and I am very interested in working for ";
String seg2 = new String();
seg2 = bizName + " as a " + posTitle;
String finalCut = new String();
finalCut = seg1 + seg2;
System.out.println("Here is your cover letter!");
System.out.println(finalCut);
}
}
Gives this output:
Welcome to tera_byteme's Simple Cover Letter Generator.
Please enter the business name.
Biz Inc.
Please enter position title.
Senior Manager
Please enter your name.
Jeff
Here is your cover letter!
My name is Jeff and I am very interested in working for Biz Inc. as a Senior Manager
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
import java.util.Scanner;
public class Box
{
public static void main(String[] args)
{
String empty = "";
String yes = "yes";
String no = "no";
String response;
String name;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
name = input.nextLine();
if(name.equals(empty))
{
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
System.out.println("Would you like the profanity filter turned on?");
response = input.nextLine();
response = response.toLowerCase();
if(response.equals(yes) || response.equals(no))
{
if(response.equals(yes))
System.out.print("Profanity filter will be turned on.");
else
System.out.print("Profanity filter will not be turned on.");
}
else
System.out.print("Invalid response, please try again.");
}
}
This displays "Please enter your name >>", but no matter what I enter there, even if it's empty, it always asks if you'd like the profanity filter turned on.
It just skips over the if that's supposed to loop forever until you actually enter a name, and I can't figure out why.
Also, I know I didn't ask this in the title, but I also can't figure out a way for the final statement to loop back to the "response = input.nextLine();" when someone doesn't enter either "yes" or "no".
If you want it to loop forever then you need to use while loop and not if, e.g.:
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name >>");
String name = input.nextLine();
while(name.isEmpty()){
System.out.println("You did not enter a name, please try again >>");
name = input.nextLine();
}
This will keep asking the user to enter the name until he enters a non empty String.
If trying to get user input into a string, using the code:
String X = input("\nDon't just press Enter: ");
and if they did't enter anything, to ask them until they do.
I've tried to check if it's null with while(x==null) but it doesn't work. Any ideas on what I am doing wrong/need to do differently?
input() is:
static String input (String prompt)
{
String iput = null;
System.out.print(prompt);
try
{
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
iput = is.readLine();
}
catch (IOException e)
{
System.out.println("IO Exception: " + e);
}
return iput;
//return iput.toLowerCase(); //Enable for lowercase
}
In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner).
Scanner input = new Scanner(System.in);
You can then use
String userInput = input.nextLine();
to retrieve the user's input. Finally, for comparing strings you should use the string.equals() method:
public String getUserInput(){
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
if (!userInput.equals("")){
//call next method
} else {
getUserInput();
}
}
What this "getUserInput" method does is to take the user's input and check that it's not blank. If it isn't blank (the first pat of the "if"), then it will continue on to the next method. However, if it is blank (""), then it will simply call the "getUserInput()" method all over again.
There are many ways to do this, but this is probably just one of the simplest ones.