01: /*
02: * JOSSO: Java Open Single Sign-On
03: *
04: * Copyright 2004-2008, Atricore, Inc.
05: *
06: * This is free software; you can redistribute it and/or modify it
07: * under the terms of the GNU Lesser General Public License as
08: * published by the Free Software Foundation; either version 2.1 of
09: * the License, or (at your option) any later version.
10: *
11: * This software is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * Lesser General Public License for more details.
15: *
16: * You should have received a copy of the GNU Lesser General Public
17: * License along with this software; if not, write to the Free
18: * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
19: * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
20: */
21: package org.josso.gateway.session.service;
22:
23: import org.apache.commons.logging.Log;
24: import org.apache.commons.logging.LogFactory;
25: import org.josso.util.id.AbstractIdGenerator;
26:
27: import java.security.MessageDigest;
28: import java.security.NoSuchAlgorithmException;
29: import java.util.Random;
30:
31: /**
32: * This is an implementation of a session id generatod based on Jakarta Tomcat 5.0
33: * session id generation.
34: * This implementation is thread safe.
35: *
36: * @author <a href="mailto:sgonzalez@josso.org">Sebastian Gonzalez Oyuela</a>
37: * @version $Id: SessionIdGeneratorImpl.java 508 2008-02-18 13:32:29Z sgonzalez $
38: */
39:
40: public class SessionIdGeneratorImpl extends AbstractIdGenerator
41: implements SessionIdGenerator {
42:
43: private static final Log logger = LogFactory
44: .getLog(SessionIdGeneratorImpl.class);
45:
46: private int _sessionIdLength = 16;
47:
48: /**
49: * Generate and return a new session identifier.
50: */
51: public synchronized String generateId() {
52:
53: byte random[] = new byte[16];
54:
55: // Render the result as a String of hexadecimal digits
56: StringBuffer result = new StringBuffer();
57: int resultLenBytes = 0;
58: while (resultLenBytes < _sessionIdLength) {
59: getRandomBytes(random);
60: random = getDigest().digest(random);
61: for (int j = 0; j < random.length
62: && resultLenBytes < _sessionIdLength; j++) {
63: byte b1 = (byte) ((random[j] & 0xf0) >> 4);
64: byte b2 = (byte) (random[j] & 0x0f);
65: if (b1 < 10)
66: result.append((char) ('0' + b1));
67: else
68: result.append((char) ('A' + (b1 - 10)));
69: if (b2 < 10)
70: result.append((char) ('0' + b2));
71: else
72: result.append((char) ('A' + (b2 - 10)));
73: resultLenBytes++;
74: }
75: }
76: return (result.toString());
77:
78: }
79:
80: }
|