View Javadoc

1   /*
2    * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.opensaml.common.impl;
18  
19  import java.security.NoSuchAlgorithmException;
20  import java.security.SecureRandom;
21  
22  import org.bouncycastle.util.encoders.Hex;
23  import org.opensaml.common.IdentifierGenerator;
24  
25  /**
26   * Generates identifiers using random data obtained from a {@link java.security.SecureRandom} instance.
27   */
28  public class SecureRandomIdentifierGenerator implements IdentifierGenerator {
29  
30      /** Random number generator. */
31      private static SecureRandom random;
32  
33      /**
34       * Constructor.
35       * 
36       * @throws NoSuchAlgorithmException thrown if the SHA1PRNG algorithm is not supported by the JVM
37       */
38      public SecureRandomIdentifierGenerator() throws NoSuchAlgorithmException {
39          random = SecureRandom.getInstance("SHA1PRNG");
40      }
41  
42      /**
43       * Constructor.
44       * 
45       * @param algorithm the random number generation algorithm to use
46       * 
47       * @throws NoSuchAlgorithmException thrown if the algorithm is not supported by the JVM
48       */
49      public SecureRandomIdentifierGenerator(String algorithm) throws NoSuchAlgorithmException {
50          random = SecureRandom.getInstance(algorithm);
51      }
52  
53      /** {@inheritDoc} */
54      public String generateIdentifier() {
55          return generateIdentifier(16);
56      }
57  
58      /** {@inheritDoc} */
59      public String generateIdentifier(int size) {
60          byte[] buf = new byte[size];
61          random.nextBytes(buf);
62          return "_".concat(new String(Hex.encode(buf)));
63      }
64  }