forked from apache/commons-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomStringUtils.java
More file actions
1014 lines (944 loc) · 41.4 KB
/
RandomStringUtils.java
File metadata and controls
1014 lines (944 loc) · 41.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
/**
* Generates random {@link String}s.
* <p>
* Use {@link #secure()} to get the singleton instance based on {@link SecureRandom#SecureRandom()} which uses a secure random number generator implementing the
* default random number algorithm.
* </p>
* <p>
* Use {@link #secureStrong()} to get the singleton instance based on {@link SecureRandom#getInstanceStrong()} which uses an instance that was selected by using
* the algorithms/providers specified in the {@code securerandom.strongAlgorithms} {@link Security} property.
* </p>
* <p>
* Use {@link #insecure()} to get the singleton instance based on {@link ThreadLocalRandom#current()} <strong>which is not cryptographically secure</strong>. In addition,
* instances do not use a cryptographically random seed unless the {@linkplain System#getProperty system property} {@code java.util.secureRandomSeed} is set to
* {@code true}.
* </p>
* <p>
* Starting in version 3.17.0, the method {@link #secure()} uses {@link SecureRandom#SecureRandom()} instead of {@link SecureRandom#getInstanceStrong()}, and
* adds {@link #secureStrong()}.
* </p>
* <p>
* Starting in version 3.16.0, this class uses {@link #secure()} for static methods and adds {@link #insecure()}.
* </p>
* <p>
* Starting in version 3.15.0, this class uses {@link SecureRandom#getInstanceStrong()} for static methods.
* </p>
* <p>
* Before version 3.15.0, this class used {@link ThreadLocalRandom#current()} for static methods, which is not cryptographically secure.
* </p>
* <p>
* RandomStringUtils is intended for simple use cases. For more advanced use cases consider using Apache Commons Text's
* <a href= "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/RandomStringGenerator.html"> RandomStringGenerator</a>
* instead.
* </p>
* <p>
* The Apache Commons project provides <a href="https://commons.apache.org/proper/commons-rng/">Commons RNG</a> dedicated to pseudo-random number generation,
* that may be a better choice for applications with more stringent requirements (performance and/or correctness).
* </p>
* <p>
* Note that <em>private high surrogate</em> characters are ignored. These are Unicode characters that fall between the values 56192 (db80) and 56319 (dbff) as
* we don't know how to handle them. High and low surrogates are correctly dealt with - that is if a high surrogate is randomly chosen, 55296 (d800) to 56191
* (db7f) then it is followed by a low surrogate. If a low surrogate is chosen, 56320 (dc00) to 57343 (dfff) then it is placed after a randomly chosen high
* surrogate.
* </p>
* <p>
* #ThreadSafe#
* </p>
*
* @see #secure()
* @see #secureStrong()
* @see #insecure()
* @see SecureRandom#SecureRandom()
* @see SecureRandom#getInstanceStrong()
* @see ThreadLocalRandom#current()
* @see RandomUtils
* @since 1.0
*/
public class RandomStringUtils {
private static final Supplier<RandomUtils> SECURE_SUPPLIER = RandomUtils::secure;
private static RandomStringUtils INSECURE = new RandomStringUtils(RandomUtils::insecure);
private static RandomStringUtils SECURE = new RandomStringUtils(SECURE_SUPPLIER);
private static RandomStringUtils SECURE_STRONG = new RandomStringUtils(RandomUtils::secureStrong);
private static final char[] ALPHANUMERICAL_CHARS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9' };
private static final int ASCII_0 = '0';
private static final int ASCII_9 = '9';
private static final int ASCII_A = 'A';
private static final int ASCII_z = 'z';
private static final int CACHE_PADDING_BITS = 3;
private static final int BITS_TO_BYTES_DIVISOR = 5;
private static final int BASE_CACHE_SIZE_PADDING = 10;
/**
* Gets the singleton instance based on {@link ThreadLocalRandom#current()}; <b>which is not cryptographically
* secure</b>; use {@link #secure()} to use an algorithms/providers specified in the
* {@code securerandom.strongAlgorithms} {@link Security} property.
* <p>
* The method {@link ThreadLocalRandom#current()} is called on-demand.
* </p>
*
* @return the singleton instance based on {@link ThreadLocalRandom#current()}.
* @see ThreadLocalRandom#current()
* @see #secure()
* @since 3.16.0
*/
public static RandomStringUtils insecure() {
return INSECURE;
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of all characters.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count) {
return secure().next(count);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
* </p>
*
* @param count the length of random string to create
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count, final boolean letters, final boolean numbers) {
return secure().next(count, letters, numbers);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters specified.
* </p>
*
* @param count the length of random string to create
* @param chars the character array containing the set of characters to use, may be null
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count, final char... chars) {
return secure().next(count, chars);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
* </p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count, final int start, final int end, final boolean letters,
final boolean numbers) {
return secure().next(count, start, end, letters, numbers);
}
/**
* Creates a random string based on a variety of options, using default source of randomness.
*
* <p>
* This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but
* instead of using an externally supplied source of randomness, it uses the internal static {@link Random}
* instance.
* </p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @param chars the set of chars to choose randoms from. If {@code null}, then it will use the set of all chars.
* @return the random string
* @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array.
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count, final int start, final int end, final boolean letters,
final boolean numbers, final char... chars) {
return secure().next(count, start, end, letters, numbers, chars);
}
/**
* Creates a random string based on a variety of options, using supplied source of randomness.
*
* <p>
* If start and end are both {@code 0}, start and end are set to {@code ' '} and {@code 'z'}, the ASCII printable
* characters, will be used, unless letters and numbers are both {@code false}, in which case, start and end are set
* to {@code 0} and {@link Character#MAX_CODE_POINT}.
*
* <p>
* If set is not {@code null}, characters between start and end are chosen.
* </p>
*
* <p>
* This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a single
* {@link Random} instance with a fixed seed and using it for each call, the same random sequence of strings can be
* generated repeatedly and predictably.
* </p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at (inclusive)
* @param end the position in set of chars to end before (exclusive)
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @param chars the set of chars to choose randoms from, must not be empty. If {@code null}, then it will use the
* set of all chars.
* @param random a source of randomness.
* @return the random string
* @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array.
* @throws IllegalArgumentException if {@code count} < 0 or the provided chars array is empty.
* @since 2.0
*/
public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
final char[] chars, final Random random) {
if (count == 0) {
return StringUtils.EMPTY;
}
if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else if (!letters && !numbers) {
end = Character.MAX_CODE_POINT;
} else {
end = 'z' + 1;
start = ' ';
}
} else if (end <= start) {
throw new IllegalArgumentException(
"Parameter end (" + end + ") must be greater than start (" + start + ")");
} else if (start < 0 || end < 0) {
throw new IllegalArgumentException("Character positions MUST be >= 0");
}
if (end > Character.MAX_CODE_POINT) {
// Technically, it should be `Character.MAX_CODE_POINT+1` as `end` is excluded
// But the character `Character.MAX_CODE_POINT` is private use, so it would anyway be excluded
end = Character.MAX_CODE_POINT;
}
// Optimizations and tests when chars == null and using ASCII characters (end <= 0x7f)
if (chars == null && end <= 0x7f) {
// Optimize generation of full alphanumerical characters
// Normally, we would need to pick a 7-bit integer, since gap = 'z' - '0' + 1 = 75 > 64
// In turn, this would make us reject the sampling with probability 1 - 62 / 2^7 > 1 / 2
// Instead we can pick directly from the right set of 62 characters, which requires
// picking a 6-bit integer and only rejecting with probability 2 / 64 = 1 / 32
if (letters && numbers && start <= ASCII_0 && end >= ASCII_z + 1) {
return random(count, 0, 0, false, false, ALPHANUMERICAL_CHARS, random);
}
if (numbers && end <= ASCII_0 || letters && end <= ASCII_A) {
throw new IllegalArgumentException(
"Parameter end (" + end + ") must be greater then (" + ASCII_0 + ") for generating digits "
+ "or greater then (" + ASCII_A + ") for generating letters.");
}
// Optimize start and end when filtering by letters and/or numbers:
// The range provided may be too large since we filter anyway afterward.
// Note the use of Math.min/max (as opposed to setting start to '0' for example),
// since it is possible the range start/end excludes some of the letters/numbers,
// e.g., it is possible that start already is '1' when numbers = true, and start
// needs to stay equal to '1' in that case.
// Note that because of the above test, we will always have start < end
// even after this optimization.
if (letters && numbers) {
start = Math.max(ASCII_0, start);
end = Math.min(ASCII_z + 1, end);
} else if (numbers) {
// just numbers, no letters
start = Math.max(ASCII_0, start);
end = Math.min(ASCII_9 + 1, end);
} else if (letters) {
// just letters, no numbers
start = Math.max(ASCII_A, start);
end = Math.min(ASCII_z + 1, end);
}
}
final StringBuilder builder = new StringBuilder(count);
final int gap = end - start;
final int gapBits = Integer.SIZE - Integer.numberOfLeadingZeros(gap);
// The size of the cache we use is an heuristic:
// about twice the number of bytes required if no rejection
// Ideally the cache size depends on multiple factor, including the cost of generating x bytes
// of randomness as well as the probability of rejection. It is however not easy to know
// those values programmatically for the general case.
// Calculate cache size:
// 1. Multiply count by bits needed per character (gapBits)
// 2. Add padding bits (3) to handle partial bytes
// 3. Divide by 5 to convert to bytes (normally this would be by 8, dividing by 5 allows for about 60% extra space)
// 4. Add base padding (10) to handle small counts efficiently
// 5. Ensure we don't exceed Integer.MAX_VALUE / 5 + 10 to provide a good balance between overflow prevention and
// making the cache extremely large
final long desiredCacheSize = ((long) count * gapBits + CACHE_PADDING_BITS) / BITS_TO_BYTES_DIVISOR + BASE_CACHE_SIZE_PADDING;
final int cacheSize = (int) Math.min(desiredCacheSize, Integer.MAX_VALUE / BITS_TO_BYTES_DIVISOR + BASE_CACHE_SIZE_PADDING);
final CachedRandomBits arb = new CachedRandomBits(cacheSize, random);
while (count-- != 0) {
// Generate a random value between start (included) and end (excluded)
final int randomValue = arb.nextBits(gapBits) + start;
// Rejection sampling if value too large
if (randomValue >= end) {
count++;
continue;
}
final int codePoint;
if (chars == null) {
codePoint = randomValue;
switch (Character.getType(codePoint)) {
case Character.UNASSIGNED:
case Character.PRIVATE_USE:
case Character.SURROGATE:
count++;
continue;
}
} else {
codePoint = chars[randomValue];
}
final int numberOfChars = Character.charCount(codePoint);
if (count == 0 && numberOfChars > 1) {
count++;
continue;
}
if (letters && Character.isLetter(codePoint) || numbers && Character.isDigit(codePoint)
|| !letters && !numbers) {
builder.appendCodePoint(codePoint);
if (numberOfChars == 2) {
count--;
}
} else {
count++;
}
}
return builder.toString();
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters specified by the string, must not be empty. If null, the set
* of all characters is used.
* </p>
*
* @param count the length of random string to create
* @param chars the String containing the set of characters to use, may be null, but must not be empty
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0 or the string is empty.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String random(final int count, final String chars) {
return secure().next(count, chars);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAlphabetic(final int count) {
return secure().nextAlphabetic(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextAlphabetic(minLengthInclusive, maxLengthExclusive);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAlphanumeric(final int count) {
return secure().nextAlphanumeric(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextAlphanumeric(minLengthInclusive, maxLengthExclusive);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126}
* (inclusive).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAscii(final int count) {
return secure().nextAscii(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126}
* (inclusive).
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextAscii(minLengthInclusive, maxLengthExclusive);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters which match the POSIX [:graph:] regular expression character
* class. This class contains all visible ASCII characters (i.e. anything except spaces and control characters).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomGraph(final int count) {
return secure().nextGraph(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Graph} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextGraph(minLengthInclusive, maxLengthExclusive);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of numeric characters.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomNumeric(final int count) {
return secure().nextNumeric(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Digit} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextNumeric(minLengthInclusive, maxLengthExclusive);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters which match the POSIX [:print:] regular expression character
* class. This class includes all visible ASCII characters and spaces (i.e. anything except control characters).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomPrint(final int count) {
return secure().nextPrint(count);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Print} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
* @deprecated Use {@link #secure()}, {@link #secureStrong()},or {@link #insecure()}.
*/
@Deprecated
public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) {
return secure().nextPrint(minLengthInclusive, maxLengthExclusive);
}
/**
* Gets the singleton instance based on {@link SecureRandom#SecureRandom()} which uses a secure random number generator (RNG) implementing the default
* random number algorithm.
* <p>
* The method {@link SecureRandom#SecureRandom()} is called on-demand.
* </p>
*
* @return the singleton instance based on {@link SecureRandom#SecureRandom()}.
* @see SecureRandom#SecureRandom()
* @since 3.16.0
*/
public static RandomStringUtils secure() {
return SECURE;
}
/**
* Gets the singleton instance based on {@link SecureRandom#getInstanceStrong()} which uses an algorithms/providers
* specified in the {@code securerandom.strongAlgorithms} {@link Security} property.
* <p>
* The method {@link SecureRandom#getInstanceStrong()} is called on-demand.
* </p>
*
* @return the singleton instance based on {@link SecureRandom#getInstanceStrong()}.
* @see SecureRandom#getInstanceStrong()
* @since 3.17.0
*/
public static RandomStringUtils secureStrong() {
return SECURE_STRONG;
}
private final Supplier<RandomUtils> random;
/**
* {@link RandomStringUtils} instances should NOT be constructed in standard programming. Instead, the class should
* be used as {@code RandomStringUtils.random(5);}.
*
* <p>
* This constructor is public to permit tools that require a JavaBean instance to operate.
* </p>
*
* @deprecated TODO Make private in 4.0.
*/
@Deprecated
public RandomStringUtils() {
this(SECURE_SUPPLIER);
}
private RandomStringUtils(final Supplier<RandomUtils> random) {
this.random = random;
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of all characters.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.16.0
*/
public String next(final int count) {
return next(count, false, false);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
* </p>
*
* @param count the length of random string to create
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.16.0
*/
public String next(final int count, final boolean letters, final boolean numbers) {
return next(count, 0, 0, letters, numbers);
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters specified.
* </p>
*
* @param count the length of random string to create
* @param chars the character array containing the set of characters to use, may be null
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.16.0
*/
public String next(final int count, final char... chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, random());
}
return random(count, 0, chars.length, false, false, chars, random());
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.
* </p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.16.0
*/
public String next(final int count, final int start, final int end, final boolean letters, final boolean numbers) {
return random(count, start, end, letters, numbers, null, random());
}
/**
* Creates a random string based on a variety of options, using default source of randomness.
*
* <p>
* This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but
* instead of using an externally supplied source of randomness, it uses the internal static {@link Random}
* instance.
* </p>
*
* @param count the length of random string to create
* @param start the position in set of chars to start at
* @param end the position in set of chars to end before
* @param letters if {@code true}, generated string may include alphabetic characters
* @param numbers if {@code true}, generated string may include numeric characters
* @param chars the set of chars to choose randoms from. If {@code null}, then it will use the set of all chars.
* @return the random string
* @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array.
* @throws IllegalArgumentException if {@code count} < 0.
*/
public String next(final int count, final int start, final int end, final boolean letters, final boolean numbers,
final char... chars) {
return random(count, start, end, letters, numbers, chars, random());
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters specified by the string, must not be empty. If null, the set
* of all characters is used.
* </p>
*
* @param count the length of random string to create
* @param chars the String containing the set of characters to use, may be null, but must not be empty
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0 or the string is empty.
* @since 3.16.0
*/
public String next(final int count, final String chars) {
if (chars == null) {
return random(count, 0, 0, false, false, null, random());
}
return next(count, chars.toCharArray());
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
*/
public String nextAlphabetic(final int count) {
return next(count, true, false);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z).
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
*/
public String nextAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) {
return nextAlphabetic(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
*/
public String nextAlphanumeric(final int count) {
return next(count, true, true);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
*/
public String nextAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) {
return nextAlphanumeric(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126}
* (inclusive).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
*/
public String nextAscii(final int count) {
return next(count, 32, 127, false, false);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126}
* (inclusive).
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
*/
public String nextAscii(final int minLengthInclusive, final int maxLengthExclusive) {
return nextAscii(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters which match the POSIX [:graph:] regular expression character
* class. This class contains all visible ASCII characters (i.e. anything except spaces and control characters).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.5
*/
public String nextGraph(final int count) {
return next(count, 33, 126, false, false);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Graph} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
*/
public String nextGraph(final int minLengthInclusive, final int maxLengthExclusive) {
return nextGraph(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of numeric characters.
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
*/
public String nextNumeric(final int count) {
return next(count, false, true);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Digit} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.5
*/
public String nextNumeric(final int minLengthInclusive, final int maxLengthExclusive) {
return nextNumeric(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Creates a random string whose length is the number of characters specified.
*
* <p>
* Characters will be chosen from the set of characters which match the POSIX [:print:] regular expression character
* class. This class includes all visible ASCII characters and spaces (i.e. anything except control characters).
* </p>
*
* @param count the length of random string to create
* @return the random string
* @throws IllegalArgumentException if {@code count} < 0.
* @since 3.5
* @since 3.16.0
*/
public String nextPrint(final int count) {
return next(count, 32, 126, false, false);
}
/**
* Creates a random string whose length is between the inclusive minimum and the exclusive maximum.
*
* <p>
* Characters will be chosen from the set of \p{Print} characters.
* </p>
*
* @param minLengthInclusive the inclusive minimum length of the string to generate
* @param maxLengthExclusive the exclusive maximum length of the string to generate
* @return the random string
* @since 3.16.0
*/
public String nextPrint(final int minLengthInclusive, final int maxLengthExclusive) {
return nextPrint(randomUtils().randomInt(minLengthInclusive, maxLengthExclusive));
}
/**
* Gets the Random.
*
* @return the Random.
*/
private Random random() {
return randomUtils().random();
}
/**