Java - Check online password - java

This is from Liang's Java Book. Basically, I have to check with a method if a certain word could be used as password.
/*
(Check password) Some websites impose certain rules for passwords. Write a
method that checks whether a string is a valid password. Suppose the password
rules are as follows:
■ A password must have at least eight characters.
■ A password consists of only letters and digits.
■ A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays Valid
Password if the rules are followed or Invalid Password otherwise.
*/
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
if (isValidPassword(password))
System.out.println("The password is valid.");
else
System.out.println("The password is not valid.");
public static boolean isValidPassword (String password) {
if (password.length() >= 8) {
// if (regex to include only alphanumeric characters?
// if "password" contains at least two digits...
return true;
}
Also, what if (not required) would I to display the exact kind of error? For instance, if I would notify the user that only a kind of error has occurred (e.g. "Your password length is OK, but there are no digits in your password")?

I would do this way:
public class Test {
public static String passwordChecker(String s){
String response = "The password";
int countdigits = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(s);
while(matcher.find()){
++countdigits;
}
if(s.length() >= 8){
response = response + ": \n-is too short (min. 8)";
}
else if(!(s.toLowerCase().matches("[a-z]+") && s.matches("[0-9]+"))){
response = response + "\n-is not alphanumeric";
}
else if(countdigits < 2){
response = response + "\n-it doesn't contains at least 2 digits";
}
else{
response = response + " ok";
}
return response;
}
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
System.out.println(passwordChecker(password));
}
}
Oops, I forgot to add the rules; well, just use System.out.println :)

Related

How to verify OTP in Java using simple loop?

I'm a Java beginner and my project consists of creating a simple program to register users for an alumni center. The process creates an ID and then provides the new user with an OTP. Next is the login (Enter ID:, Enter OTP: ).
My OTP verification method is not working. It seems to be a problem with the IF.equals declaration, the process jumps straight to the ELSE condition.
Any suggestions why?
Here is my code:
class Main {
static NewRegandLogin newRegAndLogin = new NewRegandLogin(null, null, null, null, null, null);
static ArrayList<NewRegandLogin> loginInformation = new ArrayList<>();
public static void main(String[] args) {
System.out.println(" WELCOME TO THE ALUMNI SHE-CODES SYSTEM ");
System.out.println("_________________________________\n - New Alumni registration - \n");
System.out.println("");
newRegAndLogin.registerNewGrad();
System.out.println();
System.out.println("_________________________________");
System.out.println();
System.out.println("Your new Alumni ID is: " + newRegAndLogin.getAlumniId());
System.out.println();
System.out.println("Your temporary password is:");
System.out.println(newRegAndLogin.oTp(8));
loginInformation.add(newRegAndLogin);
System.out.println("_________________________________");
System.out.println("_________________________________\n - Alumni Login - \n");
System.out.println("");
newRegAndLogin.login();
System.out.println("");
System.out.println("Please make a list of completed Courses: -->Enter 'S' to stop adding courses<--");
newRegAndLogin.setAlumniCourses();
System.out.println("_________________________________");
newRegAndLogin.setLinkedInPage();
loginInformation.add(newRegAndLogin);
//printAlumniProfile();
System.out.println("_________________________________");
newRegAndLogin.jobOffer();
}
void login() {
System.out.print("ID: ");
alumniIdImput = scanner.nextLine();
idVerification();
do {
System.out.println("Password (OTP if logging in for the first time): ");
passwordImput = scanner.nextLine();
oTpFromImput = passwordImput.toCharArray();
oTpVerification();
} while (isPasswordCorrect=false);
void oTpVerification() {
isPasswordCorrect = false;
if (oTpFromImput.equals(oTp(8))) {
isPasswordCorrect = true;
System.out.println("Logging In.....");
}else {
isPasswordCorrect = false;
System.out.println("Incorrect password.\nPlease enter valid password: 8 alpha numeric
characters(Aa,123,#,#,$,%)");
}
}
This is the oTp method
char[] oTp (int length) {
String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String smallChars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!##$%^&*_-=+/.?<>";
String values = capitalChars + smallChars + numbers + symbols;
Random oneTimePassword = new Random();
char[] password = new char[length];
for(int i = 0; i<length;i++) {
password[i] = values.charAt(oneTimePassword.nextInt(values.length()));
}
return password;
}
It seems you built a guessing game, not an OTP verification code.
You first read the OTP from user, and only then randomly generate one to copare to it.
Basically, you code expects the user to guess a random 8 character password that has not been created you, which is basically impossible...
You need to generate to OTP first, show it to the user, then ask them to input it.
I see your logic code is generate OTP code after User input. It seem so wierd bro.
Whenever you call oTp(8) function will generate new OTP.
Use should generate OTP first then store somewhere, then User input and compare it.
You need to store the generated otp somewhere. Then compare it with the input otp. Right now you are comparing it with the otp(8). And otp(8) always returns a new otp.

How can I implement String.split() in my login system?

I have a text file called UserDetails.txt that I am trying to read from.
Each line of the text file is as follows:
John : Doe : Seattle : jd3 : 1234
Jane : Doe : Olympia : jd4 : 5678
Jerry : Doe : Redmond : jd5 : 9101
And so on...
Each line has the first name, last name, username, and password of the registered user by which I am trying to search for only the last two variables (username and password).
public class LoginFrame extends javax.swing.JFrame
{
private static Scanner keyboard = new
Scanner(System.in);
String username;
String password;
String filePath = "UserDetails.txt";
public LoginFrame() {
initComponents();
}
private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {
username = jTextFieldUsername.getText();
password = jTextFieldPassword.getText();
verifyLogin(username,password,filePath);
}
public static void verifyLogin(String username,
String password, String filepath)
{
boolean match = false;
String tempUserName = "";
String tempPassword = "";
try
{
keyboard = new Scanner(new
File(filepath));
keyboard.useDelimiter("[:\n]");
while(keyboard.hasNext() && !match)
{
tempUserName = keyboard.next();
tempPassword = keyboard.next();
if(tempUserName.trim().equals(username.trim()) &&
tempPassword.trim().equals(password.trim()))
{
match = true;
}
}
keyboard.close();
System.out.print(match);
}
catch (Exception e)
{
System.out.print("Error");
}
}
This above code snippet is my original code by which I tried to use a delimiter to find the two specific values but it only seems to work if the username and password are the only two variables in the text file (with first and last names removed).
I've been reading up on the String.split() method so that I can replace my original use of the delimiter. However, I'm still struggling with how I can apply it to my text file. Many of the examples online explain how one can convert an individual line into a String array (which in my example, would have the username at index 3 and password at index 4). This is where I'm confused though. How can I implement the String.split() method without having to manually input it for every specific line? (since there are 50 users in the text file). Would it be possible to implement it with the Scanner.nextLine() method?
Here:
while(keyboard.hasNext() && !match)
{
tempUserName = keyboard.next();
tempPassword = keyboard.next();
You are reading each of the lines in pairs. You should instead call keyboard.next four times in each iteration. I am guessing that you intend to ignore the first name and last name, so you don't need to assign them to any variable:
while(keyboard.hasNext() && !match)
{
// These two lines read the first name and last name and do nothing with them
keyboard.next();
keyboard.next();
// these will read the username and password
tempUserName = keyboard.next();
tempPassword = keyboard.next();
If you want to use split, you need to call nextLine and hasNextLine instead:
while (keyboard.hasNextLine() && !match) {
String[] parts = keyboard.nextLine().split(" : ");
tempUserName = parts[2];
tempPassword = parts[3];
...
}

Selenium Webdriver Java validate name field

I am not very experienced with Selenium. I thought to test my knowledge by doing the following, validate that a name field in a form has no special character. I was not able to do so. 1st I tried to put the characters in an array and read from the array but I kept on getting Alert failure message. Then I thought of the following way and always getting output "valid".
import junit.framework.Assert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class NameField {
public static FirefoxDriver fx= new FirefoxDriver();
public static String doCheck()
{
fx.get("http://www.gogamers.com/#!blank/gs4id");
String regex = "^[A-Z0-9+$";
String str=fx.findElement(By.id("comp-iikjotq8nameField")).getText();
fx.findElement(By.id("comp-iikjotq8nameField")).sendKeys("#john");
if (str.matches("[" + regex + "]+")){
System.out.println("Invalid character in Name field");
}
else{
System.out.println("valid");
}
return str;
What I have in mind is if you give a name using sendkey(eg: John#, #john) you will get invalid message. Another thing I was thinking should I use assertion? Please suggest a best way a small sample code would be helpful.
The new code that I have tried today which is still giving me Valid, when I am expecting invalid. Can someone kindly take a look please? I tried both matches and find
public class YahooMail {
public static void main(String[] args) {
FirefoxDriver fx= new FirefoxDriver();
fx.get("https://login.yahoo.com/account/create?");
String title=fx.getTitle();
Assert.assertTrue(title.contains("Yahoo"));
//First I send a text, then I get the text
fx.findElement(By.id("usernamereg-firstName")).sendKeys("$John");
fx.findElement(By.id("usernamereg-firstName")).getText();
//This is the String I want to find
String firstName="John";
//If there are these symbols associated with the name-show invalid
String patternString = ".*$%^#:.*";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(firstName);
if(matcher.find()){
System.out.println("Invalid Name" );
}
else{
System.out.println("Valid Name");
}
}
}
You can fix your regular expression to match any non-alphanumeric characters and use Pattern and Matcher instead:
Pattern p = Pattern.compile("\\W");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println("Invalid character in Name field");
}
else {
System.out.println("valid");
}
What I did to validate a name field I used same regular expression as was used by our developers in website. Name field in my case is only accepting alphanumeric characters. First of all I created a java functions to randomly generate alphanumeric with special characters as below and then I am comparing this auto generated input with actual regular expressions. As special characters are not allowed in my case, if statement will return false and else block will be executed showing that special characters are not allowed.
//can also be used for complex passwords
public String randomSpecial(int count)
{
String characters = "~`!##$%^&*()-_=+[{]}\\|;:\'\",<.>/?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
String generatedString = RandomStringUtils.random(count, characters);
return generatedString;
}
public void TC_05_regExpression_Invalid()
{
String regex = "/^[a-zA-Z0-9- ]*$/";
WebElement element = driver.findElement(By.name("firstName"));
element.sendKeys(randomSpecial(10));
String fieldText = element.getAttribute("value");
if(fieldText.matches("["+ regex + "]+"))
{
logger.info("Valid Input: " + fieldText);
}
else
{
logger.info("InValid Input: " + fieldText + "not allowed");
}
element.clear();
}
It is working now, the problem is I was not capturing the sendKeys value. I should have used getAttribute
f.get("https://mail.yahoo.com");
f.findElement(By.id("login-username")).sendKeys("jj%jo.com");
//The getAttribute method returns the value of an attribute of an HTML Tag;
//for example if I have an input like this:
WebElement element = f.findElement(By.id("login-username"));
String text = element.getAttribute("value");
System.out.println(text);
if((text).contains("#")){
System.out.println("pass");
}
else{
System.out.println("not pass");
}
enter code here
public class Personal_loan {
public String verified_number(String inputNumber) // pass the parameter
{
String validation;
String regexNum = "[0-9]+"; //"[A-Za-z]";//"^[A-Z+$]";
if (inputNumber.matches("[" + regexNum + "]+"))
{
System.out.println("valid");
validation="valid";
}
else{
System.out.println("Invalid character in Name field");
validation="invalid";
}
return validation;
}
public String verified_str(String inputStr)
{
String regexString = "[A-Za-z]";//"^[A-Z+$]";
if (inputStr.matches("[" + regexString + "]+"))
{
System.out.println("valid");
}
else{
System.out.println("Invalid character in Name field");
}
return null;
}
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.iservefinancial.com/");
driver.findElement(By.xpath("(//DIV[#itemprop='name'])[1]")).click();
WebElement LoanAmount =driver.findElement(By.xpath("//INPUT[#id='amount_qa']"));
WebElement Income =driver.findElement(By.xpath("//INPUT[#id='income_qa']"));
LoanAmount.sendKeys("12345");
Income.sendKeys("amount");
Personal_loan pl=new Personal_loan(); //creating object
String g = LoanAmount.getAttribute("value"); // store the value in string
String incomevalue = Income.getAttribute("value");
String lavalid=pl.verified_number(g);
String income_valid = pl.verified_number(incomevalue);
System.out.println("Loan Amount "+lavalid);
System.out.println("income Amount "+income_valid);
}
}

Java split string (check given parameters)

For a Java IRC client I have a login funtion. If you type "!LOGIN user pass" it will log you in.
Right now if a user uses a space too much or only uses 1 parameter in stead of "user" + "pass" it will crash the programm due to the way I am spliting the line.
I`m having trouble to find a solution so I can make a check if string user or string pass != null..
Any suggestions would be very much appreciated!
if (line.contains("!LOGIN")){ //!LOGIN username password
String[] parts = line.split(" ");
String user = parts[4];
String pass = parts[5];
}
In general it is recommended to verify your input before parsing it, or to test if the parsing worked.
In this case you are splitting on string, which gives you no certainty.
The minimum you should do is test if you have enough chunks as expected:
String[] parts = line.split(" ");
if (parts.length >= 5) {
// your usual logic
String user = parts[4];
String pass = parts[5];
}
But it's generally better to create a pattern that (strictly) defines the acceptable input. You first validate that the input provided matches the expected pattern. (where in your pattern you decide how lenient you want to be)
something like:
public class TestPattern {
public static String[] inputTest = new String[] {
"!LOGIN user pass",
"!LOGIN user pass ",
"!LOGIN user pass",
"!LOGIN user pass",
" !LOGIN user pass",
" !LOGIN user pass "
};
public static void main(String[] argv) {
// ^ = start of line
// \\s* = 0 or more spaces
// \\s+ = 1 or more spaces
// (\\w+) = group 1 containing 1 or more word-characters (a-zA-Z etc)
// $ = end of line
Pattern pattern = Pattern.compile("^\\s*!LOGIN\\s+(\\w+)\\s+(\\w+)\\s*$");
for (String input : inputTest) {
Matcher matcher = pattern.matcher(input);
if (!matcher.find()) {
System.out.println("input didn't match login: " + input);
continue;
}
String username = matcher.group(1);
String password = matcher.group(2);
System.out.println("username[ " + username + " ], password[ " + password + " ]");
}
}
}
You can test this also with bad input like:
public static String[] inputFailed = new String[] {
"",
"! LOGIN user pass",
"!LOGINX user pass",
"!LOGIN user pass other",
"!LOGIN userpass"
};
if (line.contains("!LOGIN")){ //!LOGIN username password
String[] parts = line.split("\\s+");
String user = parts.length > 3 ? parts[4] : "";
String pass = parts.length > 4 ? parts[5] : "";
}
Use the regex as described in the comments above, then check the size of the array.

Parse Text using scanner useDelimiter

Looking to parse the following text file:
Sample text file:
<2008-10-07>text entered by user<Ted Parlor><2008-11-26>additional text entered by user<Ted Parlor>
I would like to parse the above text so that I can have three variables:
v1 = 2008-10-07
v2 = text entered by user
v3 = Ted Parlor
v1 = 2008-11-26
v2 = additional text entered by user
v3 = Ted Parlor
I attempted to use scanner and useDelimiter, however, I'm having issue on how to set this up to have the results as stated above. Here's my first attempt:
import java.io.*;
import java.util.Scanner;
public class ScanNotes {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
//String regex = "(?<=\\<)([^\\>>*)(?=\\>)";
s = new Scanner(new BufferedReader(new FileReader("cur_notes.txt")));
s.useDelimiter("[<]+");
while (s.hasNext()) {
String v1 = s.next();
String v2= s.next();
System.out.println("v1= " + v1 + " v2=" + v2);
}
} finally {
if (s != null) {
s.close();
}
}
}
}
The results is as follows:
v1= 2008-10-07>text entered by user v2=Ted Parlor>
What I desire is:
v1= 2008-10-07 v2=text entered by user v3=Ted Parlor
v1= 2008-11-26 v2=additional text entered by user v3=Ted Parlor
Any help that would allow me to extract all three strings separately would be greatly appreciated.
You can use \s*[<>]\s* as delimiter. That is, any of < or >, with any preceding and following whitespaces.
For this to work, there must not be any < or > in the input other than the ones used to mark the date and user fields in the input (i.e. no I <3 U!! in the message).
This delimiter allows empty string parts in an entry, but it also leaves empty string tokens between any two entries, so they must be discarded manually.
import java.util.Scanner;
public class UseDelim {
public static void main(String[] args) {
String content = " <2008-10-07>text entered by user <Ted Parlor>"
+ " <2008-11-26> additional text entered by user <Ted Parlor>"
+ " <2008-11-28><Parlor Ted> ";
Scanner sc = new Scanner(content).useDelimiter("\\s*[<>]\\s*");
while (sc.hasNext()) {
System.out.printf("[%s|%s|%s]%n",
sc.next(), sc.next(), sc.next());
// if there's a next entry, discard the empty string token
if (sc.hasNext()) sc.next();
}
}
}
This prints:
[2008-10-07|text entered by user|Ted Parlor]
[2008-11-26|additional text entered by user|Ted Parlor]
[2008-11-28||Parlor Ted]
See also
regular-expressions.info/Character classes
regular-expressions.info/Repetition

Categories