001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.session.mgt.eis;
020
021import org.apache.shiro.session.Session;
022import org.slf4j.Logger;
023import org.slf4j.LoggerFactory;
024
025import java.io.Serializable;
026import java.util.Random;
027
028/**
029 * Generates session IDs by using a {@link Random} instance to generate random IDs. The default {@code Random}
030 * implementation is a {@link java.security.SecureRandom SecureRandom} with the {@code SHA1PRNG} algorithm.
031 *
032 * @since 1.0
033 */
034public class RandomSessionIdGenerator implements SessionIdGenerator {
035
036    private static final Logger log = LoggerFactory.getLogger(RandomSessionIdGenerator.class);
037
038    private static final String RANDOM_NUM_GENERATOR_ALGORITHM_NAME = "SHA1PRNG";
039    private Random random;
040
041    public RandomSessionIdGenerator() {
042        try {
043            this.random = java.security.SecureRandom.getInstance(RANDOM_NUM_GENERATOR_ALGORITHM_NAME);
044        } catch (java.security.NoSuchAlgorithmException e) {
045            log.debug("The SecureRandom SHA1PRNG algorithm is not available on the current platform.  Using the " +
046                    "platform's default SecureRandom algorithm.", e);
047            this.random = new java.security.SecureRandom();
048        }
049    }
050
051    public Random getRandom() {
052        return this.random;
053    }
054
055    public void setRandom(Random random) {
056        this.random = random;
057    }
058
059    /**
060     * Returns the String value of the configured {@link Random}'s {@link Random#nextLong() nextLong()} invocation.
061     *
062     * @param session the {@link Session} instance to which the ID will be applied.
063     * @return the String value of the configured {@link Random}'s {@link Random#nextLong()} invocation.
064     */
065    public Serializable generateId(Session session) {
066        //ignore the argument - just call the Random:
067        return Long.toString(getRandom().nextLong());
068    }
069}