Java Password Code Example

1 view
Skip to first unread message

Ortiz Ullery

unread,
Aug 5, 2024, 2:42:24 PM8/5/24
to ovinhenli
TheJPasswordField class, a subclass of JTextField, provides specialized text fields for password entry. For security reasons, a password field does not show the characters that the user types. Instead, the field displays a character different from the one typed, such as an asterisk '*'. As another security precaution, a password field stores its value as an array of characters, rather than as a string. Like an ordinary text field, a password field fires an action event when the user indicates that text entry is complete, for example by pressing the Enter button.

The password is "bugaboo". The password "bugaboo" is an example only. Use secure authentication methods in production systems. You can find the entire code for this program in PasswordDemo.java. Here is the code that creates and sets up the password field:


The argument passed into the JPasswordField constructor indicates the preferred size of the field, which is at least 10 columns wide in this case. By default a password field displays a dot for each character typed. If you want to change the echo character, call the setEchoChar method. The code then adds an action listener to the password field, which checks the value typed in by the user. Here is the implementation of the action listener's actionPerformed method:


A program that uses a password field typically validates the password before completing any actions that require the password. This program calls a private method, isPasswordCorrect, that compares the value returned by the getPassword method to a value stored in a character array. Here is its code:


PasswordDemo is the Tutorial's only example that uses a JPasswordField object. However, the Tutorial has many examples that use JTextField objects, whose API is inherited by JPasswordField. See Examples That Use Text Fields for further information.


One of the ongoing criticisms of the Java command line text-basedinput/output APIs is the lack of support for command line inputpassword masking. With AWT/Swing, this is not a problem as methods areprovided to mask passwords easily.


An earlier version of this article was published here in September2002, and since then numerous letters of thanks, constructive comments,and permissions to use the source code in applications have beenreceived. This article:


If you wish to provide a graphical login dialog box for your application, you can use the AWT's TextField class, which is a text component that allows the editing of a single line of text. To mask the password field, use the setEchoChar method. For example, to set the echo char to an asterisk, you would do:


The number 8 specifies the width of the text field based on theaverage character width for the font in use. You can set the echocharacter to any character you like. Note that if you set it to zero, 0, it means that the input will be echoed and not masked.


In Swing, you can use the JPasswordField, whichallows the editing of a single line of text where the view indicatessomething was typed, but does not show the original characters. The JPasswordField class is source-compatible with the AWT's TextField used with setEchoChar. If you use the JPasswordField,the default echo character is an asterisk '*', but you can change it toany character of your choice. Again, if you set the echo character tozero, 0, it means that characters will be displayed asthey are typed and no masking will be performed. Figure 2 shows a Swinglogin dialog box where the echo character is being set to a hash sign, # using the following snippet of code:


Unlike AWT/Swing, there are no special APIs for masking command-lineinput in Java. This is a feature that has been asked for by manydevelopers. It is useful if you wish to provide a login screen forcommand-line text-based Java applications as well as server-side Javaapplications. One way to provide for such a feature is to use JavaNative Interface (JNI). This might be difficult for some Javadevelopers who do not know C/C++, or wish to keep to 100% pure Javacode.


Here I provide a solution to this problem. In the earlier version ofthis article, a UNIX-like approach to login screens, where the passwordis not echoed on the screen at all, was used. This is done by having aseparate thread that attempts to erase characters echoed to the consoleby re-writing and printing the password prompt. The code featured inthat article can still be downloaded from the forums along with code for improvements.


One of the most asked-for features, however, was replacing the echoedcharacters with asterisks "*". Therefore, this article starts byproviding a simple solution for password masking, followed by animproved, more reliable, and secure code.


This solution uses a separate thread to erase the echoed charactersas they are being entered, and replaces them with asterisks. This isdone using the EraserThread class, which is shown in Code Sample 1.


The EraserThread class is used by the PasswordField class, which is shown in Code Sample 2. This class prompts the user for a password and an instance of EraserThread attempts to mask the input with "*". Note that initially a asterisk (*) will be displayed.


As an example of how to use the PasswordField class, consider the application, TestApp,shown in Sample Code 3. This application displays a prompt and waitsfor the user to enter a password. The entry is of course masked byasterisks (*).


The above simple solution suffers from one main drawback: strings should not be used for storing sensitive information such as passwords!. In the rest of the article, an improved solution is shown.


While it may seem logical to collect and store the password using Strings, they are not suitable for storing sensitive information such as passwords. This is because objects of type String are immutable -- the contents of the string cannot be changed or overwritten after use. An array of chars should be used instead. The revised PasswordField shown in Code Sample 5 has been adapted from Using Password-Based Encryption.


This article presented an overview of password masking in Java. Itdemonstrated how easy it is to mask passwords in AWT/Swingapplications, and provided a reusable pure Java solution forcommand-line text-based password masking.


Feel free to reuse, improve, and adapt the code in this article foryour applications. You can enhance it by adding methods for passwordconstraints. As an exercise, you may wish to enhance the code presentedso that a password can be of a certain length, and so that somecharacters, such as a space for example, may not be allowed in apassword.


I'm making an auth service so I've been looking for some good Java/Groovy implementations of password + salt hashing. I've found this article on crackstation along with a code example and decided to make it mine. First thing I noticed is SHA1 and only 1000 iterations so I changed those to SHA256 and 90510(still have to test the performance on the server and perhaps increase it to at least 100k).


One thing however kind of struck me. The result string is "[iterations]:[salt as hex]:[hash as hex]". Why are iterations added to the result? Wouldn't that be insecure? Wouldn't that be akin to giving away a piece of the key? Or am I just too paranoid.


I have removed it, but I'm wondering why is it there? What is the purpose of showing that? In case the default number of iterations changes? Should the number of iterations be randomized to a degree?


Much like the salt, the iteration count isn't expected to be kept secret from attackers. It does make the job of attackers slightly more difficult if they don't know the iteration count since that adds one piece of info they have to find elsewhere. But that generally isn't expected to be a hurdle that they are unable to overcome.


By storing the iteration value alongside the password you make it easier for the iteration count to be updated on the system while still supporting the existing passwords until they can be changed. Your password checking routine always knows the appropriate number of iterations to try when matching a password hash for each particular user. Otherwise you'd have to try to accommodate different past and current possible iteration counts within the password checking code.


Randomizing the number of iterations doesn't really add much value since attackers aren't limited to cracking tools with hardcoded iteration counts or using precomputed rainbow tables with a certain number of iterations.


In the domain of digital security, password hashing stands as a critical line of defense against unauthorized access. However, the landscape of hashing algorithms has evolved significantly, with some methods becoming obsolete and newer, more secure techniques emerging. This article delves into why traditional methods like SHA-512 are no longer sufficient, the importance of salting and slowing down hashing processes, and provides practical Java code examples for modern password hashing techniques.


Salting involves adding a random string to each password before hashing. This practice thwarts rainbow table attacks, where precomputed hash tables are used for cracking passwords. By ensuring that each password hash is unique, salting effectively neutralizes this threat.


Modern password hashing algorithms intentionally slow down the hashing process to deter attacks. This approach makes brute-force attacks impractical by increasing the computational and time resources required to crack each password. Here's how they achieve this:


To verify a password using any hashing algorithm, the typical approach is to hash the input password using the same algorithm and parameters (like salt, iteration count, etc.) that were used when the original password hash was created. Then, you compare the newly generated hash with the stored hash. However, with algorithms like BCrypt, Argon2, and PBKDF2, the comparison is often simplified using built-in functions that handle these steps for you.


As cyber threats evolve, so must our methods of protecting sensitive information. Employing modern password hashing techniques like BCrypt, Argon2, and PBKDF2 is essential for safeguarding user data. These methods provide robust defense mechanisms against the most common password-cracking strategies, ensuring that even if data breaches occur, the impact on password integrity is minimized. Developers and security professionals must stay informed about the latest advancements in cryptographic practices and continuously update their security measures accordingly.

3a8082e126
Reply all
Reply to author
Forward
0 new messages