0% found this document useful (0 votes)
38 views5 pages

Java Password Initialization Logic

This Java code defines an InitData class that extends the AppCompatActivity class. The InitData class initializes data by validating user input for username and password. It checks that the username and password are not blank, validates the username, checks the password strength and history, and updates the password in the database if valid. It also defines methods to check the password policy and validate the last five passwords.

Uploaded by

Arindam Basu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views5 pages

Java Password Initialization Logic

This Java code defines an InitData class that extends the AppCompatActivity class. The InitData class initializes data by validating user input for username and password. It checks that the username and password are not blank, validates the username, checks the password strength and history, and updates the password in the database if valid. It also defines methods to check the password policy and validate the last five passwords.

Uploaded by

Arindam Basu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

package [Link].

woodPro;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

public class InitData extends AppCompatActivity {

EditText txtUser;
EditText pwd;
EditText pwdCnf;

Button btnLogin ;

private String blockChars = "'\\;";

private InputFilter inputfilter = new InputFilter() {


@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned
dest, int dstart, int dend) {

if(source!=null && [Link]((""+source))){


return "";
}

return null;
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_init_data);

if ([Link].SDK_INT > 9) {
[Link] policy = new
[Link]().permitAll().build();
[Link](policy);
}

ActionBar actionBar = getSupportActionBar();


[Link]([Link].itc_42) ;
[Link](true);
[Link](true);

txtUser = (EditText)findViewById([Link]);
pwd = (EditText)findViewById([Link]);
pwdCnf =(EditText)findViewById([Link]);

[Link](new InputFilter[]{inputfilter});
[Link](new InputFilter[]{inputfilter});
[Link](new InputFilter[]{inputfilter});

btnLogin = (Button)findViewById([Link]);

[Link](new [Link]() {
@Override
public void onClick(View v) {
if(!checkBlank())
{
[Link](getApplicationContext(),"Username/Password can't
be blank!",Toast.LENGTH_SHORT).show();
}
else if (!ValidateUserName())
{
[Link](getApplicationContext(),"Username
Invalid!",Toast.LENGTH_SHORT).show();
}
else
if([Link]().toString().trim().equalsIgnoreCase([Link]().toString().tr
im()))
{
[Link](getApplicationContext(),"Password can't be same
as username!",Toast.LENGTH_SHORT).show();
}

else if (!ValidatePwdPolicy([Link]().toString()))
{
[Link](getApplicationContext(),"Password should be
alphanumeric with special characters \n and 8 or more characters
long!",Toast.LENGTH_SHORT).show();
}
else if(isLastFive([Link]().toString()))
{
[Link](getApplicationContext(),"Password should not be
same as last 5 passwords!",Toast.LENGTH_SHORT).show();
}
else if (!
[Link]().toString().equals([Link]().toString()))
{
[Link](getApplicationContext(),"Password and Confirm
Password not same!",Toast.LENGTH_SHORT).show();
}
else
{

if(updatePwd()) {
Session lock = new Session(getApplicationContext());
[Link]("0");
[Link](getApplicationContext(), "Password updated
Successfully!", Toast.LENGTH_SHORT).show();
[Link]();
}
else{
[Link](getApplicationContext(), "Failed to Update
Password!", Toast.LENGTH_SHORT).show();
}

}
}
});

public boolean checkBlank()


{
if([Link]().toString().trim().isEmpty() ||
[Link]().toString().trim().isEmpty() ||
[Link]().toString().trim().isEmpty())
return false;
else
return true;
}

public boolean ValidateUserName()


{
Context c = [Link]();
DBHelper db = new DBHelper(c);

ConfigRecord cfUsr = new ConfigRecord();


cfUsr = [Link]("USER");

if(commonUtil.sha256([Link]().toString().toUpperCase().trim()).equalsIgnor
eCase([Link]()))
return true;
else
return false;
}

public boolean ValidatePwdPolicy(String pswrd)


{

if([Link]()>=8 && isAlpha(pswrd) &&isNumeric(pswrd) &&


isSpecialChar(pswrd))
return true;
else
return false;
}
//*********************PAssword Policy

private boolean isAlpha(String pwd)


{
Boolean flag = false;
flag=[Link](".*[a-zA-Z]+.*");
return flag;
}

public boolean isNumeric(String pwd)


{
Boolean flag = false;
flag=[Link](".*[0-9]+.*");
return flag;

public boolean isSpecialChar(String pwd)


{

if([Link]("[a-zA-Z0-9]*"))
return false;
else
return true;

public boolean isLastFive(String pswrd)


{
DBHelper db = new DBHelper(getApplicationContext());

if([Link](pswrd))
return true;
else
return false;
}
//*************************************

public boolean updatePwd()


{
try{
String strCred = [Link]().toString();
DBHelper db = new DBHelper(getApplicationContext());
[Link](strCred);
[Link](strCred);
[Link]();
return true;

}
catch (Exception ex)
{
[Link]("Update Password Exception:"+[Link]());
return false;
}

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate([Link].menu_exit, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch ([Link]()) {
case [Link].action_exit:

[Link] builder = new


[Link]([Link]);
[Link]("Exit Application?").setPositiveButton("Yes",
dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return true;
case [Link].action_settings:

Intent i = new
Intent(getApplicationContext(),[Link]);
startActivity(i);

return true;
default:
return [Link](item);
}
}
[Link] dialogClickListener = new
[Link]() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
finishAffinity();
break;

case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
[Link]();
break;
}
}
};
@Override
public void onBackPressed() {
// do nothing.
[Link] builder = new [Link]([Link]);
[Link]([Link].dialog_title);
[Link]("Exit Application?").setPositiveButton("Yes",
dialogClickListener)
.setNegativeButton("No",
dialogClickListener).setIcon([Link]).show();
}
}

Common questions

Powered by AI

Initiating an AlertDialog for exit confirmation in the InitData class enhances user interaction by providing a fail-safe mechanism against accidental exits, which could lead to data loss or require reentry of information . It respects user intention by confirming the decision to exit, thus contributing to a positive user experience (UX) by reducing unintended closures and ensuring users have the final say in the application’s lifecycle . This approach enhances perceived application quality and usability.

The InitData class extends AppCompatActivity, which enables it to utilize backward-compatible features of the ActionBar and enhance the UI experience with newer Android features that maintain compatibility with older versions of Android . This subclass grants access to a more flexible toolbar and customizable UI elements, such as setting a logo to the ActionBar, which enhances the application’s aesthetic customization capabilities while ensuring wider device compatibility.

Upon a successful password update in the InitData class, a new session is initiated by creating a Session object, which presumably manages user session data . It sets the version to '0', which could indicate a refreshed or initial state for session tracking . This approach likely ensures that session-related data is reset, preventing unauthorized access that might be tied to an old session state. This method emphasizes maintaining a secure session lifecycle post credential updates.

In the InitData class, the password update process involves verifying that the new password meets defined security policies and then updating it in the database if validated . The DBHelper class plays a crucial role by interacting with the database, executing the update queries to store the new password and maintain a history of past passwords . DBHelper ensures password changes are persisted in the database and the history is updated to prevent reuse, handling crucial data integrity and security aspects of credential management .

Explicit text input validation in the InitData class focuses on disallowing specific special characters but may inadvertently permit others that could be exploited if they are not handled uniformly across all validation scenarios . This selective filtering might inadvertently leave the system vulnerable to other injection types that exploit overlooked characters or constructs. Improvements could include implementing comprehensive validation libraries that standardize input sanitation and uniform application of validation both client-side and server-side, ensuring holistic protection against varying injection techniques.

The InitData codebase, while functional, could benefit from enhanced readability and maintainability by adopting current best practices. Currently, it lacks clear separation of concerns and encapsulates too much logic within single methods, reducing clarity . Implementing modular design principles, like extracting helper methods for specific tasks, enhancing documentation, and applying the Model-View-Controller (MVC) pattern, can increase maintainability. Clear commenting and consistent naming conventions would further aid code comprehension and streamlining future modifications.

The InitData class utilizes input filtering to block specific characters, such as single quotes and semicolons, from being entered into credential fields . This approach helps prevent SQL injection attacks by disallowing characters commonly used in malicious queries . By filtering these characters, the application reduces the risk of being manipulated through crafted inputs that could alter SQL queries and gain unauthorized access or corrupt database integrity, thus enhancing the security of the system.

The InitData class implements several security measures to enhance user authentication. It checks for non-blank entries for username and password to prevent empty credentials . The username is validated against a hashed value stored in the database to ensure authenticity . Passwords must adhere to a policy requiring a minimum length of 8 characters, including alphanumeric and special characters, enhancing password strength . Additionally, it checks that the password is not identical to the last five used passwords, which helps prevent reuse of compromised passwords . These measures collectively strengthen user login security by enforcing strict credential requirements and preventing common vulnerabilities like password reuse and weak passwords.

The password validation mechanism in the InitData class mandates that passwords must be at least 8 characters, include alphanumeric and special characters, and not be identical to the user's last five passwords . These criteria significantly strengthen password security by ensuring complexity and uniqueness . However, a potential weakness is the reliance on pattern matching that may not account for the strength of combinations or predictability of sequences users may choose . Additionally, since the validation is done client-side, it may not adequately protect against brute force attacks unless complemented with server-side checks.

The "PermitAll" thread policy in the InitData class allows all network operations to be executed on the main thread, which is generally not recommended as it can lead to unresponsive UI if network requests are slow or encounter issues . This setting temporarily bypasses the network-on-main-thread exception, providing simplicity at the cost of potentially compromising the responsiveness and stability of the application . Therefore, while it might be convenient for development, its use in production environments could degrade user experience and should be carefully evaluated against best practices, which encourage offloading such tasks to background threads or using asynchronous calls.

You might also like