]> git.mxchange.org Git - juser-login-core.git/blob - src/org/mxchange/jusercore/model/user/UserUtils.java
Use string builder
[juser-login-core.git] / src / org / mxchange / jusercore / model / user / UserUtils.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jusercore.model.user;
18
19 import java.security.SecureRandom;
20 import java.text.MessageFormat;
21 import java.util.Random;
22 import org.apache.commons.codec.digest.Crypt;
23 import org.mxchange.jcore.BaseFrameworkSystem;
24 import org.mxchange.jusercore.container.login.LoginContainer;
25
26 /**
27  * An utilities class for users
28  * <p>
29  * @author Roland Haeder<roland@mxchange.org>
30  */
31 public class UserUtils extends BaseFrameworkSystem {
32
33         /**
34          * Password alphabet
35          */
36         private static final String PASSWORD_ALPHABET = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY0123456789-/?!_+#@";
37
38         /**
39          * Minimum password length
40          */
41         private static final Integer PASSWORD_MINIMUM_LENGTH = 5;
42
43         /**
44          * Random number generator
45          */
46         private static final Random RANDOM_NUMBER_GENERATOR;
47
48         /**
49          * Static initializer
50          */
51         static {
52                 // Init RNG
53                 RANDOM_NUMBER_GENERATOR = new SecureRandom();
54         }
55
56         /**
57          * Creates a pseudo-random password with given length
58          * <p>
59          * @param length Length of the password
60          * <p>
61          * @return Pseudo-random password
62          */
63         public static String createRandomPassword (final Integer length) {
64                 // Parameter should be valid
65                 if (null == length) {
66                         // Throw NPE
67                         throw new NullPointerException("length is null");
68                 } else if (length < PASSWORD_MINIMUM_LENGTH) {
69                         // To weak passwords
70                         throw new IllegalArgumentException(MessageFormat.format("Password length {0} is to short, minimum: {1}", length, PASSWORD_MINIMUM_LENGTH));
71                 }
72
73                 // Init variable
74                 StringBuilder password = new StringBuilder(length);
75
76                 // Start creating it
77                 for (int i = 0; i < length; i++) {
78                         // Generate random number
79                         int pos = RANDOM_NUMBER_GENERATOR.nextInt(PASSWORD_ALPHABET.length());
80
81                         // Get char at this position and add it to the final password
82                         password.append(String.valueOf(PASSWORD_ALPHABET.charAt(pos)));
83                 }
84
85                 // Should have the wanted length
86                 assert (password.length() == length) : "Password length " + password.length() + " doesn't match requested: " + length;
87
88                 // Return it
89                 return password.toString();
90         }
91
92         /**
93          * Hashes given user password and adds a salt to it
94          * <p>
95          * @param userPassword User password to be hashed
96          * <p>
97          * @return Hashed user password
98          */
99         public static String encryptPassword (final String userPassword) {
100                 // Is it null or empty?
101                 if (null == userPassword) {
102                         // Throw NPE
103                         throw new NullPointerException("userPassword is null");
104                 } else if (userPassword.isEmpty()) {
105                         // Empty passwords are hardcoded not allowed due to security risks
106                         throw new IllegalArgumentException("userPassword is empty");
107                 }
108
109                 // Generate large number
110                 String number = Long.toString(RANDOM_NUMBER_GENERATOR.nextLong() * 10_000_000_000L);
111
112                 // Generate salt
113                 String salt = Crypt.crypt(number);
114
115                 // First encrypt password
116                 String encryptedPassword = Crypt.crypt(userPassword, salt);
117
118                 // Return it
119                 return encryptedPassword;
120         }
121
122         /**
123          * Checks if password from container matches the updatedUser's password
124          * <p>
125          * @param container   Container holding user instance and unencrypted
126          *                    password
127          * @param updatedUser Updated user instance from database
128          * <p>
129          * @return Whether the password matches
130          */
131         public static boolean ifPasswordMatches (final LoginContainer container, final User updatedUser) {
132                 // Validate parameters
133                 if (null == container) {
134                         // Throw NPE
135                         throw new NullPointerException("container is null");
136                 } else if (null == updatedUser) {
137                         // And again NPE ...
138                         throw new NullPointerException("updatedUser is null");
139                 } else if (container.getUser() == null) {
140                         // NPE for user in container
141                         throw new NullPointerException("container.user is null");
142                 } else if (container.getUserPassword() == null) {
143                         // NPE for user password in container
144                         throw new NullPointerException("container.userPassword is null");
145                 } else if (container.getUserPassword().isEmpty()) {
146                         // Empty password in container
147                         throw new IllegalArgumentException("container.userPassword is empty");
148                 }
149
150                 // First encrypt password
151                 String encryptedPassword = Crypt.crypt(container.getUserPassword(), updatedUser.getUserEncryptedPassword());
152
153                 // Is it matching?
154                 return encryptedPassword.equals(updatedUser.getUserEncryptedPassword());
155         }
156
157         /**
158          * No instance from this class
159          */
160         private UserUtils () {
161         }
162 }