1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.core.spring.security;
20
21 import com.fasterxml.uuid.Generators;
22 import com.fasterxml.uuid.NoArgGenerator;
23 import java.security.SecureRandom;
24 import java.util.UUID;
25 import org.apache.commons.text.RandomStringGenerator;
26 import org.passay.PasswordGenerator;
27
28 public final class SecureRandomUtils {
29
30 private static final SecureRandom RANDOM = new SecureRandom();
31
32 private static final PasswordGenerator PASSWORD_GENERATOR = new PasswordGenerator(RANDOM);
33
34 private static final RandomStringGenerator FOR_PASSWORD = new RandomStringGenerator.Builder().
35 usingRandom(RANDOM::nextInt).
36 withinRange('0', 'z').
37 filteredBy(Character::isLetterOrDigit).
38 get();
39
40 private static final RandomStringGenerator FOR_LETTERS = new RandomStringGenerator.Builder().
41 usingRandom(RANDOM::nextInt).
42 withinRange('a', 'z').
43 get();
44
45 private static final RandomStringGenerator FOR_NUMBERS = new RandomStringGenerator.Builder().
46 usingRandom(RANDOM::nextInt).
47 withinRange('0', '9').
48 get();
49
50 private static final NoArgGenerator UUID_GENERATOR = Generators.timeBasedEpochGenerator(RANDOM);
51
52 public static String generateRandomPassword(final int tokenLength) {
53 return FOR_PASSWORD.generate(tokenLength);
54 }
55
56 public static String generateRandomLetter() {
57 return FOR_LETTERS.generate(1);
58 }
59
60 public static String generateRandomLetters(final int length) {
61 return FOR_LETTERS.generate(length);
62 }
63
64 public static String generateRandomNumber() {
65 return FOR_NUMBERS.generate(1);
66 }
67
68 public static String generateRandomNonAlphanumericChar(final char[] characters) {
69 return new RandomStringGenerator.Builder().
70 usingRandom(RANDOM::nextInt).
71 filteredBy(codePoint -> {
72 boolean found = false;
73 for (int i = 0; i < characters.length && !found; i++) {
74 found = codePoint == Character.codePointAt(characters, i);
75 }
76
77 return found;
78 }).get().generate(1);
79 }
80
81 public static int generateRandomInt(final int startInclusive, final int endExclusive) {
82 return startInclusive + RANDOM.nextInt(endExclusive - startInclusive);
83 }
84
85 public static UUID generateRandomUUID() {
86 return UUID_GENERATOR.generate();
87 }
88
89 public static PasswordGenerator passwordGenerator() {
90 return PASSWORD_GENERATOR;
91 }
92
93 private SecureRandomUtils() {
94
95 }
96 }