You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.6 KiB

  1. import java.math.BigInteger;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.util.regex.Pattern;
  5. public class PasswordValidator {
  6. int minLength = 6;
  7. boolean requireUppercase = true;
  8. boolean requireLowercase = true;
  9. boolean requireDigit = true;
  10. private final Pattern uppercasePattern = Pattern.compile("^(?=.*[A-Z]).+$");
  11. private final Pattern lowercasePattern = Pattern.compile("^(?=.*[a-z]).+$");
  12. private final Pattern digitPattern = Pattern.compile("^(?=.*\\d).+$");
  13. public boolean validate(String password) {
  14. if (password.length() < minLength) {
  15. return false;
  16. } else if (requireUppercase && !uppercasePattern.matcher(password).matches()) {
  17. return false;
  18. } else if (requireLowercase && !lowercasePattern.matcher(password).matches()) {
  19. return false;
  20. } else if (requireDigit && !digitPattern.matcher(password).matches()) {
  21. return false;
  22. }
  23. return true;
  24. }
  25. public int getMinLength() {
  26. return minLength;
  27. }
  28. public void setMinLength(int minLength) {
  29. this.minLength = minLength;
  30. }
  31. public boolean isRequireUppercase() {
  32. return requireUppercase;
  33. }
  34. public void setRequireUppercase(boolean requireUppercase) {
  35. this.requireUppercase = requireUppercase;
  36. }
  37. public boolean isRequireLowercase() {
  38. return requireLowercase;
  39. }
  40. public void setRequireLowercase(boolean requireLowercase) {
  41. this.requireLowercase = requireLowercase;
  42. }
  43. public boolean isRequireDigit() {
  44. return requireDigit;
  45. }
  46. public void setRequireDigit(boolean requireDigit) {
  47. this.requireDigit = requireDigit;
  48. }
  49. public static String getSHA1Hash(String input) {
  50. if (input.length() > 0) {
  51. try {
  52. MessageDigest md = MessageDigest.getInstance("SHA-1");
  53. byte[] messageDigest = md.digest(input.getBytes());
  54. // Convert byte array into signum representation
  55. BigInteger no = new BigInteger(1, messageDigest);
  56. // Convert message digest into hex value
  57. StringBuilder hashtext = new StringBuilder();
  58. hashtext.append(no.toString(16));
  59. // Add preceding 0s to make it 32 bit
  60. while (hashtext.length() < 32) {
  61. hashtext.insert(0, "0");
  62. }
  63. return hashtext.toString();
  64. } catch (NoSuchAlgorithmException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. return null;
  69. }
  70. }