Convert one string password to all asterisks - java

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;

Related

Why won't my buffered `String` match with the `RegEx` pattern?

I've created a bluetooth data listener that stores incoming data into a String then checks whether it matches a regular expression pattern then resets the String. This is done because the data does not arrive whole in one instance so that I can manipulate with it when I get the full text. For example when I send "Hello Android!" to my device via bluetooth with my method and print the data, it would be printed like this:
#1 New data! "H"
#2 New data! "ello Android!
As you can see, the whole string cannot be sent at one instance which means that two strings get sent instead and I'm sure that most people know about that. That is why I am using RegEx to help me with that.
Instead, I am sending a randomly generated number between two different characters then try to parse them. For example "<128>". Now, I want to get the whole number so that I can use it, like parse it to an int or something like that. But only when my String buffer gets the whole data that is being sent which is determined by a RegEx pattern that goes like ([<])(-?\d+)([>]). character<followed by any positive/negative number followed by character '>'.
The problem is that it does not match the pattern at all for unknown reasons.
String szBuffer = "";
if(mmInputStream.available() > 0) {
StringBuilder builder = new StringBuilder();
byte[] bData = new byte[1024];
while(mmInputStream.available() > 0) {
int read = mmInputStream.read(bData);
builder.append(new String(bData, 0, read, StandardCharsets.UTF_8));
}
szBuffer += builder.toString();
Log.d("SZ_BUFFER", szBuffer); // For this example, "<128>" gets sent into pieces.
// <n>
if(Pattern.matches("([<])(-?\\d+)([>])", szBuffer)) {
Log.d("SZ_BUFFER_ISMATCH", "MATCH!");
szBuffer = ""; // Reset the buffer for new data
}
else
Log.d("SZ_BUFFER_ISMATCH", "NO MATCH...");
}
Here's a live output:
D/SZ_BUFFER: <
D/SZ_BUFFER_ISMATCH: NO MATCH...
D/SZ_BUFFER: <128>
D/SZ_BUFFER_ISMATCH: NO MATCH...
As you can see, it gets sent into two pieces, but when it gets the whole text together it should be a match, but isn't. Why? If I replace szBuffer with a constant String like this:
if(Pattern.matches("([<])(-?\\d+)([>])", "<128>"))
It's a match, meaning that the pattern should be correct, but when it checks for szBuffer it is never a match.
According to the docs, Pattern.matches(regex,string) is equivalent to Pattern.compile(regex).matcher(string).matches(), which is equivalent to string.matches(regex). This means that you are checking if the entire string matches the regex. If you want to check if the string contains your end-of-string marker, you can use Matcher.find instead:
Pattern pattern = Pattern.compile("([<])(-?\\d+)([>])");
String szBuffer = "";
if(mmInputStream.available() > 0) {
...
szBuffer += convertedBytes;
Log.d("SZ_BUFFER", szBuffer);
// <n>
if(pattern.matcher(szBuffer).find()) {
Log.d("SZ_BUFFER_ISMATCH", "MATCH!");
szBuffer = "";
}
else
Log.d("SZ_BUFFER_ISMATCH", "NO MATCH...");
}
The problem was that the data contains invisible characters which was confirmed by getting the data's length being wrong. The solution is to check every character then store them only if they match a certain criteria like this regular expression method:
for(char c : builder.toString().toCharArray()) {
String s = String.valueOf(c);
if(Pattern.matches("<|>|-|-?\\d+", s)){
szBuffer += s;
}
}
This is not the best nor cleanest solution, but it does solve my problem. I am still learning Regular Expressions and the many many combinations in algorithms. All new recommendations are welcome and will be added below this one.

Deleting content of every string after first empty space

How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));

Best way to trim exactly one quote from each side of Java string

I want to be able to trim one quote from each side of a java string. Here are some examples.
"foo" -> foo
"foo\"" -> foo\"
"\"foo\"" -> \"foo\"
I'm currently using StringUtils.trim from common lang but when I end the string with a escaped quote, it trims that too because they are consecutive. I want to be able to trim exactly one quote.
I ended up using org.apache.commons.lang3.StringUtils.substringBetween and it works.
You may also use the substring() method and trim the first and last characters on condition although it's a bit long.
trimedString= s.substring((s.charAt(0)=='"')?1:0 , (s.charAt(s.length()-1)=='"')?s.length()-1:s.length());
I prefer to use this String method
public String[] split(String regex)
basically if you feed in the quotation mark then you will get an array of strings holding all of the chunks between your quotation marks.
String[] parts = originalString.split("\"");
String quoteReduced = parts[0];
for (int i = 1; i < (parts.length() -1); i++){
quoteReduced = quoteReduced.concat( parts[i] +"\"" );
}
quoteReduced = quoteReduced.concat( "\"" +parts[parts.length()-1]);
While it may not be the most straight forward it is the way that I would get around this. The first piece and last piece could be included in the loop but would require an if statement.

Replace special characters from a String

im finding a problem when doing a replace special characters using the replaceAll method.
i have this piece of code:
public static String replaceSpecialCharacters(String cadena) {
cadena = cadena.replaceAll("[âãáàä]", "a");
cadena = cadena.replaceAll("[ÂÃÁÀÄ]", "A");
cadena = cadena.replaceAll("[éèêë]", "e");
cadena = cadena.replaceAll("[ÉÈÊË]", "E");
cadena = cadena.trim();
return cadena;
}
when a string like "Álamont" fot instance comes, the method returns right the string "Alamont", however this string returned in the replace is not the same than "Alamont", first if I see the count attribute of the string it says its "8" instead of "7"....and if I tri to do:
if (cadena.equalsIgnoreCase("Alamont")) {
System.out.println("i've got ya!!");
}
it nevers goes in...im sure the problemas is in the replace character...can someone help me??
thanks a lot in advance
You should cleanup your question. It’s not clear, what you mean with “the method returns right the string "Alamont", however this string returned in the replace is not the same than "Alamont" ”, and it is not clear why you are surprised that the returned String might have a different length if you use trim or why you expect "Alamont" to be equal to "atico".
However, removing accents and other diacritical marks in a String can be easier than performing dozens of replace operations and risking to forget one:
import java.text.Normalizer;
…
s=Normalizer.normalize(s, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}", "");
This sounds suspiciously like your input values are using combining characters. There's nothing wrong with this, but you should expect the String length to change.
There are ways to normalize your strings to use the non-combining version of the character ... but I forget.... there it is, Normalization tutorial ... that link is causing my browser (firefox, in ie it works better) to slow down, but it is the real link!... maybe the Normalizer JavaDoc will be enough

How to delete duplicated characters in a string?

Okay, I'm a huge newbie in the world of java and I can't seem to get this program right. I am suppose to delete the duplicated characters in a 2 worded string and printing the non duplicated characters.
for example:I input the words "computer program." the output should be "cute" because these are the only char's that are not repeated.
I made it until here:
public static void main(String[] args) {
System.out.print("Input two words: ");
String str1 = Keyboard.readString();
String words[] = str1.split(" ");
String str2 = words[0] + " ";
String str3 = words[words.length - 1] ;
}
but i don't know how to output the characters. Could someone help me?
I don't know if I should use if, switch, for, do, or do-while...... I'm confused.
what you need is to build up logic for your problem. First break the problem statement and start finding solution for that. Here you go for steps,
Read every character from a string.
Add it to a collection, but before adding that, just check whether it exists.
If it exists just remove it and continue the reading of characteer.
Once you are done with reading the characters, just print the contents of collection to console using System.out.println.
I will recommend you to refer books like "Think like A Programmer". This will help you to get started with logic building.
Just a hint: use a hash map (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html).
Adding following code after last line of your main program will resolve your issue.
char[] strChars = str2.toCharArray();
String newStr="";
for (char c : strChars) {
String charStr = ""+c;
if(!str3.contains(charStr.toLowerCase()) && !str3.contains(charStr.toUpperCase())){
newStr+=c;
}
}
System.out.println(newStr);
This code loops through all the characters of the first word and check if the second string contains that character (In any form of case Lower or Upper). If it is not containing, adding it to output string and at the end printing it.
Hope this will work in your case.
How about doing it in just 1 line?
str = str.replaceAll("(.)(?=.*\\1)", "");

Categories

Resources