001    /**
002     * Copyright 2005-2013 The Kuali Foundation
003     *
004     * Licensed under the Educational Community License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.opensource.org/licenses/ecl2.php
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.kuali.rice.kim.sesn;
017    
018    import java.security.SecureRandom;
019    
020    /**
021     * This class generates a random string for creating Distributed Session Tickets 
022     * 
023     * @author Kuali Rice Team (rice.collab@kuali.org)
024     *
025     */
026    public class SessionIdGenerator {
027    
028        /** The array of printable characters to be used in our random string. */
029        private static final char[] PRINTABLE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345679"
030            .toCharArray();
031    
032        private static final SecureRandom randomizer = new SecureRandom();
033    
034        public static String getNewString() {
035            final byte[] random = getNewStringAsBytes();
036    
037            return convertBytesToString(random);
038        }
039    
040    
041        private static byte[] getNewStringAsBytes() {
042            final byte[] random = new byte[40];
043    
044            randomizer.nextBytes(random);
045            
046            return random;
047        }
048    
049        private static String convertBytesToString(final byte[] random) {
050            final char[] output = new char[random.length];
051            for (int i = 0; i < random.length; i++) {
052                final int index = Math.abs(random[i] % PRINTABLE_CHARACTERS.length);
053                output[i] = PRINTABLE_CHARACTERS[index];
054            }
055    
056            return new String(output);
057        }
058    }