How to access to the text inside a Swing JPasswordField object? - java

In a JFrame class I have a JPasswordField object, something like this:
pswdTextField = new JPasswordField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");
I try to access to its inserted content (the password inserted by a user) by the following lines of code:
char[] pswd = pswdTextField.getPassword();
System.out.println("Password: " + pswd.toString());
The problem is that when I go to print this content I obtain the following output: Password: [C#d5c0f9 and not the inserted password
Why? What is it means? How can I obtain the inserted password?
Tnx
Andrea

Why? What is it means?
If you go through docs than you got this reasons.
For stronger security, it is recommended that the returned character
array be cleared after use by setting each character to zero.
How can I obtain the inserted password?
You can get password by,
char[] pswd = pswdTextField.getPassword();
String password=new String(pswd);
Or, you can directly print on System.out.print
System.out.print(pswd); // It override ...print(char[]) method
// without concat with another String.
Edit
Please note that, If you concat char[] with String than it will inherit Object.toString() method.
System.out.print("Password: " +pswd);// It will print like Password: [C#d5c0f9

pswdTextField.getText() is what you were looking for. toString() will not return the text inside a JPasswordField().
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of: getClass().getName() + '#' +
Integer.toHexString(hashCode())
so use
System.out.println("Password: " +pswdTextField.getText());

getText() is depreciated for JPasswordField
in Java source, its written above getText() definition
" For security reasons, this method is deprecated. "
so getPassword() is preferred.
The problem you are facing is that you are printing an array using System.out.println()
either create a string using that character array
or use for loop to access each element one by one
for(int i=0;i < charArray.length;i++)
System.out.print (charArray[i]);

Related

Convert one string password to all asterisks

I want to encrypt the password when it shows out in registration report, instead of showing the real password I would like to encrypt all the value to an asterisk (*) I tried to replace all character one-by-one to asterisk * but I think that is not the right way to achieve the result.
String s1="mypassword";
String replaceString=s1.replaceAll("a","*");
replaceString=s1.replaceAll("b","*");
replaceString=s1.replaceAll("c","*");
replaceString=s1.replaceAll("d","*");
replaceString=s1.replaceAll("e","*");
replaceString=s1.replaceAll("f","*");
replaceString=s1.replaceAll("g","*");
replaceString=s1.replaceAll("h","*");
replaceString=s1.replaceAll("i","*");
replaceString=s1.replaceAll("j","*");
replaceString=s1.replaceAll("k","*");
replaceString=s1.replaceAll("l","*");
replaceString=s1.replaceAll("m","*");
replaceString=s1.replaceAll("n","*");
replaceString=s1.replaceAll("o","*");
replaceString=s1.replaceAll("p","*");
replaceString=s1.replaceAll("q","*");
replaceString=s1.replaceAll("r","*");
replaceString=s1.replaceAll("s","*");
replaceString=s1.replaceAll("t","*");
replaceString=s1.replaceAll("u","*");
replaceString=s1.replaceAll("v","*");
replaceString=s1.replaceAll("w","*");
replaceString=s1.replaceAll("x","*");
replaceString=s1.replaceAll("y","*");
replaceString=s1.replaceAll("z","*");
replaceString=s1.replaceAll("A","*");
replaceString=s1.replaceAll("B","*");
replaceString=s1.replaceAll("C","*");
replaceString=s1.replaceAll("D","*");
replaceString=s1.replaceAll("E","*");
replaceString=s1.replaceAll("F","*");
replaceString=s1.replaceAll("G","*");
replaceString=s1.replaceAll("H","*");
replaceString=s1.replaceAll("I","*");
replaceString=s1.replaceAll("J","*");
replaceString=s1.replaceAll("K","*");
replaceString=s1.replaceAll("L","*");
replaceString=s1.replaceAll("M","*");
replaceString=s1.replaceAll("N","*");
replaceString=s1.replaceAll("O","*");
replaceString=s1.replaceAll("P","*");
replaceString=s1.replaceAll("Q","*");
replaceString=s1.replaceAll("R","*");
replaceString=s1.replaceAll("S","*");
replaceString=s1.replaceAll("T","*");
replaceString=s1.replaceAll("U","*");
replaceString=s1.replaceAll("V","*");
replaceString=s1.replaceAll("W","*");
replaceString=s1.replaceAll("X","*");
replaceString=s1.replaceAll("Y","*");
replaceString=s1.replaceAll("Z","*");
replaceString=s1.replaceAll("0","*");
replaceString=s1.replaceAll("1","*");
replaceString=s1.replaceAll("2","*");
replaceString=s1.replaceAll("3","*");
replaceString=s1.replaceAll("4","*");
replaceString=s1.replaceAll("5","*");
replaceString=s1.replaceAll("6","*");
replaceString=s1.replaceAll("7","*");
replaceString=s1.replaceAll("8","*");
replaceString=s1.replaceAll("9","*");
System.out.println(replaceString);
If s1 contains only the password, you'd want to mask all characters, and you'd end up with a string of the same length, consisting entirely of stars. This can be constructed directly:
replaceString = "*".repeat(s1.length());
Or, don't show anything about the password at all. Passwords are something that you want to give as little information as possible about, because information can make it (marginally or substantially) easier to guess/crack.
You can show something with a fixed number of stars; but I contend that's not showing anything useful, other than "this user has a password", which is presumably the same for all users.
Leave it out, use that space in the report for something else that provides information to the reader.
If you want to substitute your String with all asterisks, you can try as follow;
String s1="mypassword";
String replaceString="*";
replaceString = replaceString.repeat(s1.length());
String s1="mypassword";
String pass = s1.replaceAll("[\\W\\w]","*")
as per the code you can send the static value in the frontend or backend with ******* or in the worst case you can use replaceAll with regular expression to match all different passwords which are possible.
Security issues have been brought up already, so I'm just going to focus on the actual "task" here.
There's multiple ways to do this. One of them I would probably choose is this:
Instead of replacing them, as mentioned before, you can just create a new String that is the same length as your password string but fill it only with asterisks. This is pretty much what everybody has suggested already but I'm trying to keep it simple, as it seems like you're more on the beginner-side.
// We start off with an empty new String
String newString = "";
// Then we create a loop that adds a asterisk to the new String exactly, this is called x times where x is the length of the original passwordString
for (int i = 0; i < oldString.length; i++) { // This is a normal for-loop, if you don't know this concept yet, just google 'for-loop java'
newString = newString + "*"; // Here we set the newString to itself-i.e. the current content of the String plus an asterisk.
}
After this loop, we have a new String that has exactly as many characters as the old one but they're all asterisks. Now we could potentially replace the old String with the content of the new one, if that is what you want to do.
oldString = newString;

Convert strings in an array to Title Case - JAVA

I have an array of objects (customer) that has components: first_Name & last_Name. I am trying to convert both the first name and last name of each customer to title case. I have tried making several different methods that will convert strings to title case, but all of them have failed. This is the last thing I have tried and I cannot figure out why it would not capitalize the first letter of the first name and the first letter of the last name.
for (Customer c : customers){
c.setFirst_name(c.getFirst_name().charAt(0).toUpperCase());
}
I have checked that the first name and last name indeed contain an only-letter string with a lower case letter as the first letter in each. The error intellisense is giving me is that "char cannot be dereferenced"
This method capitalizes the 1st char of the string and makes the rest lower case:
public static String toTitle(String s) {
return (s.length() > 0) ? s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase() : "";
}
so use it:
for (Customer c : customers){
c.setFirst_name(toTitle(c.getFirst_name()));
c.setLast_name(toTitle(c.getLast_name()));
}
String.charAt() returns a char, which is a primitive type and therefore does not have methods. So the toUpperCase() call is not allowed there.
What you probably want is to create a Character object there, maybe a String. We don't know because you never showed the setFirst_name() signature.
String values is immutable. You try to change the first cahracter. That does not work. You must make a new string: Extract the first character of the original string, convert it to upper case and append the rest of the original string.

How to convert char[] to string?

I have a question in this case how to convert char[] to string?(Must explicitly convert the char[] to a String) sorry being a novice programmer i am asking this.
String str3 = "Dad saw I was Playing";
System.out.println(str3.toCharArray() + "\n" + str3.toLowerCase() );
System.out.println(str3.toCharArray());
Output:
[C#1034bb5 //this is what I am getting for first str3.tochararray(),how to resolve this?
dad saw i was playing
Dad saw I was Playing
You can use Arrays.toString(char[]) (or create your own method if you prefer a different formatting). Something like,
String str3 = "Dad saw I was Playing";
System.out.println(Arrays.toString(str3.toCharArray()));
System.out.println(str3.toCharArray() + "\n" + str3.toLowerCase() );
This first calls toString over CharArray which outputs [C#1034bb5 and then append it to the rest of the string and print.
System.out.println(str3.toCharArray()); -- This calls the overridden method in PrintStream class which can interpret char array and print it.
You can explicitly convert your char array to string and print.

User Class Information

How would you put your first name and last name together with a period(.) in the middle and assign it to a String of FullName.
FullName = +FirstName '.'+ LastName;
It has got a big red 'X' next to the line. The error is
The method FirstName() is undefined for the type Username
The method LastName() is undefined for the type Username
The operator + is undefined for the argument type(s) String
Syntax error on token ""."", delete this token.
Any suggestions?
You're on the right lines, but your syntax is a little off.
String fullName = firstName + "." + lastName;
NOTE: I've used the proper naming conventions, which can be found here.
This works because you declare a new String, fullName. You then assign it the value of firstName, then a ".", then the value of lastName. This code assumes that firstName and lastName has already been declared previously.
If you wanted to be more efficient..
Then you can use a class called a StringBuilder. This is because concatenating String objects in Java is considered bad practise and highly inefficient, and StringBuilder offers a nicer solution to it. Sample code would be as follows.
StringBuilder builder = new StringBuilder();
builder.append(firstName);
builder.append(".");
builder.append(lastName);
String fullName = builder.toString();
Edit: Here's a link to the working code: http://ideone.com/KIIOgo

string to char array, showing silly characters

It is a really simple question but I need an another eye to look at my code:
String strtr = "iNo:";
char[] queryNo = strtr.toCharArray();
System.out.println(queryNo + " =this is no");
and the output is:
[C#177b4d3 =this is no
What are these characters, do you have any idea?
That's how toString() is implemented for arrays.
The [C denotes that is a char array, 177b4d3 is its hashcode.
You may want to look at
System.out.println(Arrays.toString(queryNo) + " =this is no");
if you want to see your original String again, you need this:
System.out.println((new String(queryNo)) + " =this is no");
Arrays do not override toString(), it is inherited from Object.toString as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
you are printing the object
queryno, as queryno is a character array of on dimension and java is an object oriented language which holds every thing in the form of classes it gives the class name [C to your array where [ denotes total dimension and C denotes character type of array, Rest is the hashcode of the object.
You are trying to print the array and that is the reason you get gibberish. Try using Arrays.toString(queryNo) and you will see what you expected.

Categories

Resources