Jpasswordfield java to string

Class JPasswordField

JPasswordField is a lightweight component that allows the editing of a single line of text where the view indicates something was typed, but does not show the original characters. You can find further information and examples in How to Use Text Fields, a section in The Java Tutorial.

JPasswordField is intended to be source-compatible with java.awt.TextField used with echoChar set. It is provided separately to make it easier to safely change the UI for the JTextField without affecting password entries.

NOTE: By default, JPasswordField disables input methods; otherwise, input characters could be visible while they were composed using input methods. If an application needs the input methods support, please use the inherited method, enableInputMethods(true) .

Warning: The JPasswordField will not show the original characters that were typed, instead displaying alternative text or graphics. However this doesn’t prevent the password from appearing in the system memory. For handling confidential information such as the password text, refer to the relevant section at Secure Coding Guidelines.

Читайте также:  Css задать ширину рамки

Warning: Swing is not thread safe. For more information see Swing’s Threading Policy.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .

Источник

Java jpasswordfield getpassword to string code example

Solution 1: This works for me and helps you to build a Stringified password: Solution 2: Actually, here’s the Sun implementation of : The only in there is a call to , which calls , which in turn copies characters directly into the ‘s buffer. And the output: (I put question marks there because I cannot past unprintable characters) -M Solution: I would suggest you create a JTextField and it should point to a JPasswordField.

Why does JPasswordField.getPassword() create a String with the password in it?

This works for me and helps you to build a Stringified password:

String passText = new String(passField.getPassword()); 

Actually, here’s the Sun implementation of getPassword() :

public char[] getPassword() < Document doc = getDocument(); Segment txt = new Segment(); try < doc.getText(0, doc.getLength(), txt); // use the non-String API >catch (BadLocationException e) < return null; >char[] retValue = new char[txt.count]; System.arraycopy(txt.array, txt.offset, retValue, 0, txt.count); return retValue; > 

The only getText in there is a call to getText(int offset, int length, Segment txt) , which calls getChars(int where, int len, Segment txt) , which in turn copies characters directly into the Segment ‘s buffer. There are no Strings being created there.

Then, the Segment ‘s buffer is copied into the return value and zeroed out before the method returns.

In other words: There is no extra copy of the password hanging around anywhere . It’s perfectly safe as long as you use it as directed.

Ok, my bad. All the bells started ringing as soon as I saw the call to getText() without noticing that it was actually introduced by me with the Action listener here’s a stacktrace

PasswordTest$1.getText() line: 14 PasswordTest$1(JTextField).fireActionPerformed() line: not available PasswordTest$1(JTextField).postActionEvent() line: not available JTextField$NotifyAction.actionPerformed(ActionEvent) line: not available SwingUtilities.notifyAction(Action, KeyStroke, KeyEvent, Object, int) line: not available 
 import java.awt.event.*; import javax.swing.*; public class PasswordTest < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JPasswordField passField = new JPasswordField() < @Override public String getText() < System.err.println("Awhooa: " + super.getText()); //breakpoint return null; >>; passField.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent evt) < char[] p = passField.getPassword(); System.out.println(p); >>); frame.add(passField); frame.setVisible(true); frame.pack(); > > 

And here is the console output:

And for the actual call to getPassword(), maybe I am missing something, but where is Segment’s buffer zeroed? I see an array copy, but not a zeroing. The returned array will be zeroed by myself, but Segment’s array is still there.

import java.util.Arrays; public class ZeroingTest < public static void main(String[] args) < char[] a = ; char[] b = new char[a.length]; System.arraycopy(a, 0, b, 0, b.length); System.out.println("Before zeroing: " + Arrays.toString(a) + " " + Arrays.toString(b)); Arrays.fill(a, '\0'); System.out.println("After zeroing: " + Arrays.toString(a) + " " + Arrays.toString(b)); > > 
Before zeroing: [a, b, c] [a, b, c] After zeroing: [?, ?, ?] [a, b, c] 

(I put question marks there because I cannot past unprintable characters)

How to encrypt/decrypt a password from a, The problem is when a user create his account his information is stored in DB but the password is a String so everyone can see what the password it is . I want to hash the password into my java program first then store it into DB. But I don’t understand how to that because I use «Windows Builder» to do the …

Getting password in string format directly from JPasswordField

I would suggest you create a JTextField and it should point to a JPasswordField.

 JTextField enterNewPassword = new JPasswordField(); 

This will hide the text input and will automatically convert the password to plain string also. No conversion is required

Java — Why getText() in JPasswordField was deprecated, The Java documentation explains: Deprecated. As of Java 2 platform v1.2, replaced by getPassword. Fetches a portion of the text represented by the component. Returns an empty string if length is 0. For security reasons, this method is deprecated. Use the getPassword method instead.

JPasswordField returning some hash code converted into string type

getPassword() returns a char[] . The toString() on it does not return the contents as a string as you assume.

Try new String(txtPwd.getPassword()).equals(«s123») .

However, there is a reason it is a char[] and not a String. Try looking up the security aspect of it in the javadoc.

Note: this should have been a comment but is way too long for this. Consider giving the upvotes to the answers in the linked thread

As already indicated by mKorbel there is a rather complete discussion in getText() vs getPassword() .

Further, read the Swing tutorial about JPasswordField which contains a nice example on how you should compare the password (by comparing char arrays, and not by converting the char array to a String ) — small copy paste from the tutorial:

private static boolean isPasswordCorrect(char[] input) < boolean isCorrect = true; char[] correctPassword = < 'b', 'u', 'g', 'a', 'b', 'o', 'o' >; if (input.length != correctPassword.length) < isCorrect = false; >else < isCorrect = Arrays.equals (input, correctPassword); >//Zero out the password. Arrays.fill(correctPassword,'0'); return isCorrect; > 

The reason why you should compare char arrays is nicely explained by Hovercraft Full Of Eels in his answer in the linked SO question at the start of this answer.

private void loginActionPerformed(java.awt.event.ActionEvent evt) < char[] pass = passwordField.getPassword(); String mypass = pass.toString(); String user = (String) combo.getSelectedItem(); try < String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; Class.forName(driver); String db = "jdbc:odbc:LoginDB"; con = DriverManager.getConnection(db); st = con.createStatement(); String sql = "select * from Table2"; rs = st.executeQuery(sql); while (rs.next()) < String AdminNewID = rs.getString("AdminID"); String AdminNewPass = rs.getString("AdminPassword"); if ((user.equals(AdminNewID)) && pass.equals(AdminNewPass)) < MyApp form = new MyApp(); form.setVisible(true); >else < this.res.setText(" Incorrect User Name or Password"); >> > catch (Exception ex) < >> 

Swing Examples — Create Password Field, Following example showcase how to create and use a password field in a Java Swing application. We are using the following APIs. JPasswordField − To create a password field. JPasswordField.getPassword () − To get the password.

JPasswordField.getPassword() is still not secured?

When you retrieve the password from the JPasswordField you just get a copy. The Document object in the JPasswordField still has an own character array containing the password. I guess this is the value that you see in your memory viewer.

Now an idea would be to clear the JPasswordField after one has verified the password:

Ironically this raises an UndoableEditEvent containing a javax.swing.text.GapContent$RemoveUndo object which stores the password as String object — something which we tried to avoid in the first place.

Java — Why does JPasswordField.getPassword() create a, Swing’s JPasswordField has the getPassword() method that returns a char array. My understanding of this is that the array can be zeroed immediately after use so that you do not have sensitive things hanging around in memory for long. The old way to retrieve the password was to use getText(), which returns a String object, but it has been Usage exampleString passText = new String(passField.getPassword());Feedback

Источник

Jpasswordfield java to string

Constructs a new JPasswordField , with a default document, null starting text string, and 0 column width.

Constructs a new JPasswordField that uses the given text storage model and the given number of columns.

Method Summary

Methods inherited from class javax.swing.JTextField

Methods inherited from class javax.swing.text.JTextComponent

Methods inherited from class javax.swing.JComponent

Methods inherited from class java.awt.Container

Methods inherited from class java.awt.Component

Methods inherited from class java.lang.Object

Constructor Detail

JPasswordField

Constructs a new JPasswordField , with a default document, null starting text string, and 0 column width.

JPasswordField

Constructs a new JPasswordField initialized with the specified text. The document model is set to the default, and the number of columns to 0.

JPasswordField

public JPasswordField(int columns)

Constructs a new empty JPasswordField with the specified number of columns. A default model is created, and the initial string is set to null .

JPasswordField

Constructs a new JPasswordField initialized with the specified text and columns. The document model is set to the default.

JPasswordField

public JPasswordField(Document doc, String txt, int columns)

Constructs a new JPasswordField that uses the given text storage model and the given number of columns. This is the constructor through which the other constructors feed. The echo character is set to ‘*’, but may be changed by the current Look and Feel. If the document model is null , a default one will be created.

Method Detail

getUIClassID

updateUI

Reloads the pluggable UI. The key used to fetch the new interface is getUIClassID() . The type of the UI is TextUI . invalidate is called after setting the UI.

getEchoChar

Returns the character to be used for echoing. The default is ‘*’. The default may be different depending on the currently running Look and Feel. For example, Metal/Ocean’s default is a bullet character.

setEchoChar

public void setEchoChar(char c)

Sets the echo character for this JPasswordField . Note that this is largely a suggestion, since the view that gets installed can use whatever graphic techniques it desires to represent the field. Setting a value of 0 indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField .

echoCharIsSet

public boolean echoCharIsSet()

Returns true if this JPasswordField has a character set for echoing. A character is considered to be set if the echo character is not 0.

cut

Invokes provideErrorFeedback on the current look and feel, which typically initiates an error beep. The normal behavior of transferring the currently selected range in the associated text model to the system clipboard, and removing the contents from the model, is not acceptable for a password field.

copy

Invokes provideErrorFeedback on the current look and feel, which typically initiates an error beep. The normal behavior of transferring the currently selected range in the associated text model to the system clipboard, and leaving the contents from the model, is not acceptable for a password field.

getText

Returns the text contained in this TextComponent . If the underlying document is null , will give a NullPointerException . For security reasons, this method is deprecated. Use the * getPassword method instead.

getText

@Deprecated public String getText(int offs, int len) throws BadLocationException

Fetches a portion of the text represented by the component. Returns an empty string if length is 0. For security reasons, this method is deprecated. Use the getPassword method instead.

setText

Sets the text of this TextComponent to the specified text. If the text is null or empty, has the effect of simply deleting the old text. When text has been inserted, the resulting caret location is determined by the implementation of the caret class. Note that text is not a bound property, so no PropertyChangeEvent is fired when it changes. To listen for changes to the text, use DocumentListener .

getPassword

Returns the text contained in this TextComponent . If the underlying document is null , will give a NullPointerException . For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.

paramString

Returns a string representation of this JPasswordField . This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null .

getAccessibleContext

Returns the AccessibleContext associated with this JPasswordField . For password fields, the AccessibleContext takes the form of an AccessibleJPasswordField . A new AccessibleJPasswordField instance is created if necessary.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Оцените статью