From: Roland Haeder <roland@mxchange.org>
Date: Mon, 11 Apr 2016 19:11:48 +0000 (+0200)
Subject: Added method createRandomPassword() for creating pseudo-random passwords
X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=359a83f079abbab7be39ffe1f5cf96f43f6b1966;p=juser-activity-core.git

Added method createRandomPassword() for creating pseudo-random passwords
---

diff --git a/src/org/mxchange/jusercore/model/user/UserUtils.java b/src/org/mxchange/jusercore/model/user/UserUtils.java
index b98c7f9..e7a299d 100644
--- a/src/org/mxchange/jusercore/model/user/UserUtils.java
+++ b/src/org/mxchange/jusercore/model/user/UserUtils.java
@@ -16,6 +16,9 @@
  */
 package org.mxchange.jusercore.model.user;
 
+import java.security.SecureRandom;
+import java.text.MessageFormat;
+import java.util.Random;
 import org.apache.commons.codec.digest.Crypt;
 import org.mxchange.jcore.BaseFrameworkSystem;
 import org.mxchange.jusercore.container.login.LoginContainer;
@@ -27,6 +30,65 @@ import org.mxchange.jusercore.container.login.LoginContainer;
  */
 public class UserUtils extends BaseFrameworkSystem {
 
+	/**
+	 * Password alphabet
+	 */
+	private static final String PASSWORD_ALPHABET = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY0123456789-/?!_+#@";
+
+	/**
+	 * Minimum password length
+	 */
+	private static final Integer PASSWORD_MINIMUM_LENGTH = 5;
+
+	/**
+	 * Random number generator
+	 */
+	private static final Random RANDOM_NUMBER_GENERATOR;
+
+	/**
+	 * Static initializer
+	 */
+	static {
+		// Init RNG
+		RANDOM_NUMBER_GENERATOR = new SecureRandom();
+	}
+
+	/**
+	 * Creates a pseudo-random password with given length
+	 * <p>
+	 * @param length Length of the password
+	 * <p>
+	 * @return Pseudo-random password
+	 */
+	public static String createRandomPassword (final Integer length) {
+		// Parameter should be valid
+		if (null == length) {
+			// Throw NPE
+			throw new NullPointerException("length is null");
+		} else if (length < PASSWORD_MINIMUM_LENGTH) {
+			// To weak passwords
+			throw new IllegalArgumentException(MessageFormat.format("Password length {0} is to short, minimum: {1}", length, PASSWORD_MINIMUM_LENGTH));
+		}
+
+		// Init variable
+		String password = "";
+
+		// Start creating it
+		for (int i = 0; i < length; i++) {
+			// Generate random number
+			int pos = RANDOM_NUMBER_GENERATOR.nextInt(PASSWORD_ALPHABET.length());
+
+			// Get char at this position and add it to the final password
+			String dummy = password.concat(String.valueOf(PASSWORD_ALPHABET.charAt(pos)));
+		}
+
+		// Should have the wanted length
+		assert (password.length() == length) : "Password length " + password.length() + " doesn't match requested: " + length;
+
+		// Return it
+		return password;
+	}
+
 	/**
 	 * Hashes given user password and adds a salt to it
 	 * <p>