blob: 0120344d9ce1a1e9b412a6067eb6116ac7c57676 (
plain) (
blame)
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
|
package org.openslx.imagemaster.util;
import java.security.SecureRandom;
/**
* Generate secure random strings
*
*/
public class RandomString
{
private static final String lettersSpecial = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+-$%&/()=?@";
private static final String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final SecureRandom random = new SecureRandom();
/**
* Generate a random string.
*
* @param length the length of the string
* @param specialChars whether to use special charachters or not
* @return the generated string
*/
public static String generate( int length, boolean specialChars )
{
String used = ( specialChars ) ? lettersSpecial : letters;
String result = "";
for ( int i = 0; i < length; i++ ) {
int index = (int) ( random.nextDouble() * used.length() );
result += used.substring( index, index + 1 );
}
return result;
}
/**
* Generate random binary data.
*
* @param length number of bytes to generate
* @return the generated binary data, as byte array
*/
public static byte[] generateBinary( int length )
{
byte[] result = new byte[ length ];
random.nextBytes( result );
return result;
}
}
|