Password must contains :
1 Upper letter
1 lower letter
1 digit
1 special symbol
Minimum 8 symbols
Here it is my regex:
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#_$%^&*-]).{8,}$
But when i try to validate for example with password: Test_123 it returns me false
here is my code :
public class PasswordCheck {
static Logger logger = Logger.getLogger(CommonHelper.class);
private static final String PASSWORD_PATTERN = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#_$%^&*-]).{8,}$";
private Pattern pattern;
private Matcher matcher;
public PasswordCheck() {
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
*
* #param password
* password for validation
* #return true valid password, false invalid password
*/
public boolean validate(final String password) {
matcher = pattern.matcher(password);
System.out.println(password);
System.out.println(matcher.matches());
return matcher.matches();
}
}
I just try it to set new String in validate function with the same text: Test_1523 and return me true but when i post this string via rest service and pass it to the function returns me false
No matter if you are using regular expressions or other means to validate those strings - but please: don't push everything into one piece of code or regex.
You want to create code that is easy to read and maintain; and a single regex containing so much "coded" knowledge wont help with that. I have more than once used something like
interface PasswordValidator {
boolean isValid(String input);
String getErrorMessage();
}
To then create various classes implementing such an interface. And finally, you simply create one object per implementation class; and you can put those into some static list. And then validating means: just run all validator objects in that list. On fail, you can directly ask for the error message for the user (so you can tell him exactly what is missing; instead of throwing the whole rule set at him again).
Not saying that something like that is always required, but in my experience: password rules might change frequently. Hard-baking them into regexes is rarely a durable approach.
Related
Consider this method signature that I have
#Cacheable(
key="#name+'::'+#age+'::'+#country"
)
public User validate(String name, String age, String country) {
...
}
Notice the key that I have. Currently I am able to concatenate the name, age and country variables. But on top of concatenating them, I also want to convert the entire expression into a lowercase value.
For example if someone called this method like so: validate("John","24","USA"),
then I want my key to be resolved as: john::24::usa. Notice all the uppercase letters have become lowercase.
TLDR; how to write a spel expression which concatenates multiple variables and converts the entire result into lowercase?
Expression exp = new SpelExpressionParser()
.parseExpression("(#foo + '::' + #bar).toLowerCase()");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("foo", "XXX");
ctx.setVariable("bar", "YYY");
System.out.println(exp.getValue(ctx));
xxx::yyy
#RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
public void delete(#PathVariable Long userId) {
try{
this.authorService.delete(userId);
}catch(Exception e){
throw new RuntimeException("delete error");
}
}
Anybody know what url should I match for this definition "/{userId:\d+}", could you give me an example, like "/userid=1", is this right?
I guess that definition like this "/{userId:\d+}" , using regular expression in url to make sure it pass a number parameter.I am not sure about that , if anybody knows it please give me a link for further learning, thank you!
No, that expression maps /1 for example, all the digits.
The syntax {varName:regex} declares a URI variable with a regular expressions with the syntax {varName:regex} — e.g. given URL "/spring-web-3.0.5 .jar", the below method extracts the name, version, and file extension:
#GetMapping("/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
public void handle(#PathVariable String version, #PathVariable String ext) {
// ...
}
Check the complete doc here
It will match any digit. For example,
/1, /11, /123.
/{userId:\\d+} ===> map one or more digits after / to variable userId.
Regular expression for one or more digits is \d+, but since you are using it as a string you need to escape it using another \.
I once saw a talk by Douglas Crockford where, in the context of javascript, he mentioned that it could be useful to store secrets in closures.
I imagine this could be naively implemented like this in Java:
public static Supplier<String> passwordStore(String encryptedPassword){
String plainTextPassword = encryptedPassword; //do some decryption
return () -> plainTextPassword;
}
I wonder: Is there any benefit to doing this? Is it maybe in some way less secure?
No reason to do that. Store the password in the array of characters, since they must be explicitly converted to String if you want to print them out.
Consider the following example:
String stringPassword = "password";
char[] charactersPassword = new char[]{'p','a','s','s','w','o', 'r', 'd'};
System.out.println("Password: " + stringPassword); // Password: password
System.out.println("Password: " + charactersPassword); // Password: [C#6ce253f1
The main idea is you can clear the array's items, since it is not immutable (#Klitos Kyriacou).
Arrays.fill(charactersPassword, '0');
Moreover, if you store the password as a plain text - String, which is immutable, it will be available in the memory for a long time (which is still somehow accesible) until the Garbage collector takes care of it.
Anyway, it's highly recommended to look after some security library which can handle much more than inventing a new (usually still risky) way.
Here's a very "engineered" example so DO NOT USE IT IN YOUR CODE.
I think the effect can be better demonstrated with a predicate rather than a supplier.
Assume you implement a password checker as follows:
public class PasswordChecker {
private final String secretPassword;
public PasswordChecker(String secretPassword) {
this.secretPassword = secretPassword;
}
public boolean test(String password) {
return Objects.equals(this.secretPassword, password);
}
}
Then you can create an instance an pass it around:
final PasswordChecker passwordChecker = new PasswordChecker("changeit");
And somewhere else you could use it to check the password:
assertThat(passwordChecker.test("foobar")).isFalse();
However for the client which has an instance of PasswordChecker at hand, it is not so difficult to extract the password with some reflection:
Field secretPasswordField = passwordChecker.getClass().getDeclaredField("secretPassword");
secretPasswordField.setAccessible(true);
String secretPassword = (String) secretPasswordField.get(passwordChecker);
System.out.print(secretPassword);
Now here's the same thing with a closure:
final String secretPassword = "changeit";
final Predicate<String> passwordChecker = password -> Objects.equals(secretPassword, password);
Now you can't extract secretPassword from the passwordChecker.
lets say I have a url param like token=1234235asdjaklj231k209a&name=sam&firname=Mahan
how can I replace the value of the token with new one ?
I've done something similar to this with pattern and matcher before but I don't recall now
but I know there is a way to do so
Update : the token can contain any letter but &
thanks in advance
Spring has a util that handles this need gracefully. Apache httpcomponents does too. Below is a spring example.
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
public class StackOverflow {
private static class SO46303058 {
public static void main(String[] args) {
final String urlString = "https://subdomain.hostname/path/resource?token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
final URI uri = UriComponentsBuilder.fromHttpUrl(urlString)
.replaceQueryParam("token", "abc")
.build().toUri();
System.out.println(uri);
}
}
}
Don't be afraid of adding dependencies to your project, it beats reinventing the wheel.
We can consider doing a simple regex replacement, with a few caveats (q.v. below the code snippet).
String url = "token=1234235asdjaklj231k209a&name=sam&firname=Mahan";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);
url = "param1=value&token=1234235asdjaklj231k209a";
url = url.replaceFirst("\\btoken=.*?(&|$)", "token=new_value$1");
System.out.println(url);
Edge cases to consider are first that your token may be the last parameter in the query string. To cover this case, we should check for token=... ending in either an ambersand & or the end of the string. But if we don't use a lookahead, and instead consume that ambersand, we have to also add it back in the replacement. The other edge case, correctly caught by #DodgyCodeException in his comment below, is that there be another query parameter which just happens to end in token. To make sure we are really matching our token parameter, we can preface it with a word boundary in the regex, i.e. use \btoken=... to refer to it.
Output:
token=new_value&name=sam&firname=Mahan
param1=value&token=new_value
make a viewModel.
public class veiwModel(){ String token ; // and get and set for exmample }
then use Gson if u have a json text .
Gson gson = new Gson();
yourViewModel = gson.fronJson(jsonText , viewModel.class);
System.out.println(yourViewModel.getToken());
I am devicing an abstract class that will override toString() with an automated message, as such:
public abstract class AbstractTask {
abstract void run();
abstract int calculate();
private String makeMessage() {
String raw = this.getClass().toString();
// do regex stuff here!
}
#Override
public String toString() {
return makeMessage();
}
My implemented (extends AbstractTask) classes might be called something like
TaskXRQMinimize
TaskListParallell
TaskVerifyRepositoryEmpty
TaskCreateXRQs
TaskCreateZRQs
TaskSendAllSRQToTLS
The output I want to have when calling the classes toString() methods are:
Task XRQ Minimize
Task List Parallell
Task Verify Repository Empty
Task Create XRQs
Task Create ZRQs
Task Send All SRQ To TLS
I made a simple regex pattern to find these words:
([A-Z]{1}[a-z]+|[A-Z]{3}[a-z]?)
How do I implement this?
Make your toString() abstract as well, force subclasses to implement it by returning fixed string. Throw away parsing class name and using regular expressions - too fragile and with poor performance. If you really want to make it this way, at least do the computations once per class, not every time toString() is called.
As for the regular expression, I have something better: StringUtils#splitByCharacterTypeCamelCase() from Apache Commons Lang (there is really no need to reinvent some things):
StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"]
StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"]
StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"]
In your case:
//yields [Task, Send, All, SRQ, To, TLS]
StringUtils.splitByCharacterTypeCamelCase("TaskSendAllSRQToTLS")
you should use something like str.replaceAll("(\\w)([A-Z]\\w)", "$1 $2")
I have not tried this but it looks reasonable. It replaces all sequence like aBc to "a Bc".
this should put you on the right track:
Parts of the regex that you want to extract, surround with (). then
String raw = "TaskXRQMinimize";
String regexp = "([A-Z]{1}[a-z]+)([A-Z]{3})[a-z]?";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(raw);
if (matcher.find())
{
System.out.println("AFSDgaf " + matcher.groupCount());
System.out.println("afdgafd " + matcher.group(1));
System.out.println("afdgafd " + matcher.group(2));
}
I would just iterate on the name of the class and build a new String. the rule is pretty simple: if the current char is upper case and the next is lower case, then you sould insert a space before the current.