01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */
19: package org.apache.axis2.saaj.util;
20:
21: import java.util.Random;
22:
23: /** Code borrowed from AuthenticatorBase.java for generating a secure id's. */
24: public class IDGenerator {
25:
26: /** The number of random bytes to include when generating a session identifier. */
27: protected static final int SESSION_ID_BYTES = 16;
28:
29: /** A random number generator to use when generating session identifiers. */
30: protected static Random random = null;
31:
32: /**
33: * The Java class name of the random number generator class to be used when generating session
34: * identifiers.
35: */
36: protected static String randomClass = "java.security.SecureRandom";
37:
38: /**
39: * Generate and return a new session identifier.
40: *
41: * @return a new session id
42: */
43: public static synchronized String generateID() {
44: // Generate a byte array containing a session identifier
45: byte bytes[] = new byte[SESSION_ID_BYTES];
46:
47: getRandom().nextBytes(bytes);
48:
49: // Render the result as a String of hexadecimal digits
50: StringBuffer result = new StringBuffer();
51:
52: for (int i = 0; i < bytes.length; i++) {
53: byte b1 = (byte) ((bytes[i] & 0xf0) >> 4);
54: byte b2 = (byte) (bytes[i] & 0x0f);
55:
56: if (b1 < 10) {
57: result.append((char) ('0' + b1));
58: } else {
59: result.append((char) ('A' + (b1 - 10)));
60: }
61: if (b2 < 10) {
62: result.append((char) ('0' + b2));
63: } else {
64: result.append((char) ('A' + (b2 - 10)));
65: }
66: }
67: return (result.toString());
68: }
69:
70: /**
71: * Return the random number generator instance we should use for generating session identifiers.
72: * If there is no such generator currently defined, construct and seed a new one.
73: *
74: * @return Random object
75: */
76: private static synchronized Random getRandom() {
77: if (random == null) {
78: try {
79: Class clazz = Class.forName(randomClass);
80: random = (Random) clazz.newInstance();
81: } catch (Exception e) {
82: random = new java.util.Random();
83: }
84: }
85: return (random);
86: }
87:
88: }
|