View Javadoc
1   package org.springframework.security.oauth.provider.verifier;
2   
3   import org.springframework.beans.factory.InitializingBean;
4   
5   import java.security.SecureRandom;
6   import java.util.Random;
7   
8   /**
9    * Basic implementation of the verifier services that creates a random-value verifier and stores it in an in-memory map.
10   *
11   * @author Ryan Heaton
12   */
13  public class RandomValueVerifierServices implements OAuthVerifierServices, InitializingBean {
14  
15    private static final char[] DEFAULT_CODEC = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
16  
17    private Random random;
18    private int verifierLengthBytes = 6;
19  
20    public void afterPropertiesSet() throws Exception {
21      if (getRandom() == null) {
22        setRandom(new SecureRandom());
23      }
24    }
25  
26    public String createVerifier() {
27      byte[] verifierBytes = new byte[getVerifierLengthBytes()];
28      getRandom().nextBytes(verifierBytes);
29      return getVerifierString(verifierBytes);
30    }
31  
32    /**
33     * Convert these random bytes to a verifier string. The length of the byte array can be {@link #setVerifierLengthBytes(int) configured}. Default implementation
34     * mods the bytes to fit into the ASCII letters 1-9, A-Z, a-z .
35     * 
36     * @param verifierBytes The bytes.
37     * @return The string.
38     */
39    protected String getVerifierString(byte[] verifierBytes) {
40      char[] chars = new char[verifierBytes.length];
41      for (int i = 0; i < verifierBytes.length; i++) {
42        chars[i] = DEFAULT_CODEC[((verifierBytes[i] & 0xFF) % DEFAULT_CODEC.length)];
43      }
44      return new String(chars);
45    }
46  
47    /**
48     * The random value generator used to create token secrets.
49     *
50     * @return The random value generator used to create token secrets.
51     */
52    public Random getRandom() {
53      return random;
54    }
55  
56    /**
57     * The random value generator used to create token secrets.
58     *
59     * @param random The random value generator used to create token secrets.
60     */
61    public void setRandom(Random random) {
62      this.random = random;
63    }
64  
65    /**
66     * The verifier length in bytes, before being encoded to a string.
67     *
68     * @return The verifier length in bytes, before being encoded to a string.
69     */
70    public int getVerifierLengthBytes() {
71      return verifierLengthBytes;
72    }
73  
74    /**
75     * The verifier length in bytes, before being encoded to a string.
76     *
77     * @param verifierLengthBytes The verifier length in bytes, before being encoded to a string.
78     */
79    public void setVerifierLengthBytes(int verifierLengthBytes) {
80      this.verifierLengthBytes = verifierLengthBytes;
81    }
82  }