How To Mask a password input in java console - java

I'm building a login system in Java and I'm trying to mask the password input due to security measures but can't seem to find a way around it. This is what I'm Trying to do:
Username:
User1
Password:******
Here's my code to give you an idea
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner Input = new Scanner (System.in);
System.out.println("Username:");
String Username = Input.nextLine();
System.out.println("Password:");
String Password = Input.nextLine();
}
}

Try readPassword() method of java
It doesn't mask a * but it hide the input we type to console
cnsl = System.console();
char[] pwd = cnsl.readPassword("Password: ");
System.out.println("Password is: "+pwd);
like this.......

You can use Console.readPassword() from https://docs.oracle.com/javase/7/docs/api/java/io/Console.html

Related

I tried the java language using netbeans 12 with jdk version 8, but it always got an error in the output [duplicate]

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell.
If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
supports reading values with various data types.
allows masking the input when reading sensitive data.
allows selecting a value from a list.
allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

I want to take user input in string and write that string in a text file using java. But there is a problem

import java.io.*;
public class FileHandlingReadingWriting {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
FileWriter fWrite = new FileWriter("IOPinJava.txt");
String input = "";
System.out.println("Enter data to be entered in the string\n");
input = sc.next();
String i = input;
fWrite.write(i);
fWrite.flush();
fWrite.close();
}
}
when I execute this code and enter a string, only first word of the string gets written in the file. If the string is "This is a text", then only "This" gets written to the text file.
You aren't reading in the entire line with your scanner. Try input = sc.nextLine()

Weird Behaviour with the java scanner utility [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
I'm not sure how dumb I am or if I am missing something quite simple; anyhow, I am trying to get a basic username and password input from the user using the scanner utility.
I have made sure scanner was initialised correctly (Scanner sc = new Scanner(System.in)
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
The issue I am having is when I run this part of the code (above), the output I get looks like this (below) where I start inputting into the password section. Its as though it is just skipping over the first call to the scanner.
Username or Email:
Password: (this is where my input goes)
My only guess is that the scanner is taking the second printing as its input but I am not sure so any help is greatly appreciated.
p.s I will leave the entire method at the bottom incase it helps.
Thanks.
public static void loginPage() throws SQLException{
int requestCounter = 0;
do {
System.out.print("Username or Email: ");
String username = sc.nextLine();
System.out.print("\nPassword: ");
String password = sc.nextLine();
boolean validLoginRequest = accountLoginCheck(username, password);
if (validLoginRequest) {
break;
} else {
requestCounter++;
}
} while (requestCounter < 3);
if (requestCounter == 3) {
System.out.println("Too many attempts");
return;
}
System.out.print("TO MAIN MENU");
Remove \n from System.out.print("\nPassword: ");
Username or Email: myemail
Password: pass

How to restart Java method after termination

I'm new to Java and thought I would make one of the classic Username and Password validation programs which I have successfully made with no obvious bugs, however I would like the program to essentially restart the input if the user enters the in-correct information. How would I go about restarting the program successfully each time the users enters wrong information?
Code below:
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!"); //If the User-name and password are both correct then a message will tell the user that they are correct.
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct"); //If above conditions are not met then message will tell the user that they have entered the wrong user-name or password
}
}
}
I know this is extremely basic as I said I'm very new to Java (2 hours ago new).
I thought of calling the "main" method inside the else condition statement however I heard It's bas practice to use the "main" method any more times than when the program first starts.
Thanks in advance :)
I hope this is what you wanted.
import java.util.Scanner;
public class UserPass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user; //Creating user-name variable.
String pass; //Creating password variable.
boolean isValidUser = false;
while(!isValidUser) {
System.out.println("Enter username here: "); //Message to tell user to input the user-name.
user = input.nextLine(); //Taking the users user-name input.
System.out.println("Enter the password here: "); //Message to tell user to input the password.
pass = input.nextLine(); //Taking the users password input.
//Validating the users User-name and password input.
if(user.equals("Shane") && (pass.equals("Temple"))) {
System.out.println("Correct!");
isValidUser = true;
}
else {
System.out.println("The Usernname or Password that you have entered was in-correct");
isValidUser = false;
}
}
}
}

Printing string variable in Java

I'm getting some weird output when running (seemingly simple) code. Here's what I have:
import java.util.Scanner;
public class TestApplication {
public static void main(String[] args) {
System.out.println("Enter a password: ");
Scanner input = new Scanner(System.in);
input.next();
String s = input.toString();
System.out.println(s);
}
}
And the output I get after compiling successfully is:
Enter a password:
hello
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=5][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
Which is sort of weird. What's happening and how do I print the value of s?
You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,
Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);
Please read the tutorial on how to use it as it will explain all.
Edit
Please look here: Scanner tutorial
Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.
You could also use BufferedReader:
import java.io.*;
public class TestApplication {
public static void main (String[] args) {
System.out.print("Enter a password: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String password = null;
try {
password = br.readLine();
} catch (IOException e) {
System.out.println("IO error trying to read your password!");
System.exit(1);
}
System.out.println("Successfully read your password.");
}
}
input.next();
String s = input.toString();
change it to
String s = input.next();
May be that's what you were trying to do.
This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
You are printing the wrong value. Instead if the string you print the scanners object. Try this
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
If you have tried all the other answers, and it still hasn't work, you can try skipping a line:
Scanner scan = new Scanner(System.in);
scan.nextLine();
String s = scan.nextLine();
System.out.println("String is " + s);

Categories