replacing hard coded credentials - java

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.

Related

I have an error saying, syntax error on tokens, delete these tokens and many more, you can see for yourself

It says on the line String correctname="Pisay"; syntax error delete this token
package StringExple;
import java.util.Scanner;
public class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname=”Pisay";
System.out.println(“Enter your username:”);
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
if(username.equalsIgnoreCase(correctname)) {
System.out.println(“Authorized user!!”);
} else
System.out.println(“Unauthorized user!!”);
}
}
Couple of syntax issue is there, after fixing working.
Say Double Quotes " in print statements are not proper.
It's simple syntax issue if you concentrate then you should be able to fix them by own.
As you are doing 2 tests for both equals() and equalsIgnoreCase(), you may verify using equalsIgnoreCase() only because it will include equals() check also.
package sep2020;
import java.util.Scanner;
public class StringExple {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String correctname = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if (username.equalsIgnoreCase(correctname)) {
System.out.println("Authorized user!!");
} else
System.out.println("Unauthorized user!!");
}
}
Output:
Enter your username:
test
Unauthorized user!!
Enter your username:
Pisay
Authorized user!!
The adjusted code is below - the only issue is using ” opposed to ".
Also please format you code for future questions.
import java.util.Scanner;
class StringExple{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = "Pisay"; // String input
System.out.println("Enter your username:");
String username = sc.nextLine();
if(username.equals(correctname)){
System.out.println("Authorized user!!");
}else System.out.println("Unauthorized user!!");
if(username.equalsIgnoreCase(correctname)) System.out.println("Authorized user!!");
else System.out.println("Unauthorized user!!");
}
}

How can I achieve the end-goal from this position? Code throws out of bounds exception

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.

How to pass the user and password in code itself

I have an api which needs authorization for access. But I want to pass the authorization in code itself so that I do not need to enter the user id and password each time I use.
String[] apiList = { "https://example.com" };
String user, pass;
System.out.print("Enter your username:");
user = input.nextLine();
System.out.print("Enter your Password:");
pass = input.nextLine();
if (user.equals("user") && (pass.equals("password"))) {
System.out.println("welcome");
} else {
System.out.println("please try again!");
}
String user = "myusername";
String pass = "mypassword";
And remove the code which asks for user input, this way you don't have to enter it every time.
I'd only do this if it were a personal project without source control, you don't want to commit usernames and passwords to repositories especially not public repositories.
An alternative would be to store this data in a text file somewhere and load it into those variables, this text file can be outside the repository folder or you can gitignore this file.
Another way would be to use args inside the main method eg:
public static void main(String[] args) {
String user = args[0];
String pass = args[1];
}
Then you can configure them as commandline arguments in your IDE or pass them on the terminal when running your program.

Continuing specific loop (inner vs outer)?

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"))

How do I check two inputs against the key and value of a hashmap? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am just learning HashMaps, and have just written my first program using them. For some reason, my check to determine if the inputs I've entered match up with the key and it's corresponding value always returns false. Can anyone tell me why that is?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) throws FileNotFoundException {
HashMap<String, String> userPass = new HashMap<String,String>();
HashMap<String, String> userFull = new HashMap<String, String>();
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the filename to read from: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()){
String fullname=inputFile.next()+" "+inputFile.next();
String username=inputFile.next();
String pass=inputFile.nextLine();
userPass.put(username, pass);
userFull.put(username, fullname);
}
inputFile.close();
//initialize variable for use after loop
String inputUsr = null;
//checks if key/value is found
boolean b=false;
int tries=1;
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.next();
System.out.print("\nPassword: ");
String inputPass=keyboard.next();
//if inputted password equals the password of the inputted username
if(inputPass.equals(userPass.get(inputUsr)))
b=true;
System.out.println("Either the username or password is incorrect. You have "+(3-tries)+" more attempts.");
tries++;
//program quits afte 3 tries
if(tries>3){
System.exit(0);
}
}
System.out.println("Welcome "+userFull.get(inputUsr));
}
}
There are two problems in the code inside your while loop as explained below:
(1) keyboard.next() is reading the console output text i.e., reading the printed text 'Password', so replace keyboard.next() with keyboard.nextLine();
(2) You did not handle the else condition for the tries count
You can refer at the below code with inline comments:
while(b==false){
System.out.print("Login: ");
inputUsr=keyboard.nextLine();
System.out.print("\nPassword: ");
String inputPass=keyboard.nextLine();
if(inputPass.equals(userPass.get(inputUsr))) {
b=true;
} else {
System.out.println("Either the username
or password is incorrect.
You have "+(3-tries)+" more attempts.");
tries++;
}
if(tries>3){
System.exit(0);
}
}

Categories

Resources