View Javadoc
1   package org.springframework.security.oauth2.common.util;
2   
3   import java.security.SecureRandom;
4   import java.util.Random;
5   
6   /**
7    * Utility that generates a random-value ASCII string.
8    * 
9    * @author Ryan Heaton
10   * @author Dave Syer
11   */
12  public class RandomValueStringGenerator {
13  
14  	private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
15  			.toCharArray();
16  
17  	private Random random = new SecureRandom();
18  
19  	private int length;
20  
21  	/**
22  	 * Create a generator with the default length (6).
23  	 */
24  	public RandomValueStringGenerator() {
25  		this(6);
26  	}
27  
28  	/**
29  	 * Create a generator of random strings of the length provided
30  	 * 
31  	 * @param length the length of the strings generated
32  	 */
33  	public RandomValueStringGenerator(int length) {
34  		this.length = length;
35  	}
36  
37  	public String generate() {
38  		byte[] verifierBytes = new byte[length];
39  		random.nextBytes(verifierBytes);
40  		return getAuthorizationCodeString(verifierBytes);
41  	}
42  
43  	/**
44  	 * Convert these random bytes to a verifier string. The length of the byte array can be
45  	 * {@link #setLength(int) configured}. The default implementation mods the bytes to fit into the
46  	 * ASCII letters 1-9, A-Z, a-z .
47  	 * 
48  	 * @param verifierBytes The bytes.
49  	 * @return The string.
50  	 */
51  	protected String getAuthorizationCodeString(byte[] verifierBytes) {
52  		char[] chars = new char[verifierBytes.length];
53  		for (int i = 0; i < verifierBytes.length; i++) {
54  			chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)];
55  		}
56  		return new String(chars);
57  	}
58  
59  	/**
60  	 * The random value generator used to create token secrets.
61  	 * 
62  	 * @param random The random value generator used to create token secrets.
63  	 */
64  	public void setRandom(Random random) {
65  		this.random = random;
66  	}
67  	
68  	/**
69  	 * The length of string to generate.
70  	 * 
71  	 * @param length the length to set
72  	 */
73  	public void setLength(int length) {
74  		this.length = length;
75  	}
76  
77  }