001/** 002 * 003 * Copyright 2003-2007 Jive Software, 2016-2021 Florian Schmaus. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smack.util; 018 019import java.security.SecureRandom; 020import java.util.Random; 021 022public class RandomUtil { 023 024 static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>() { 025 @Override 026 protected SecureRandom initialValue() { 027 return new SecureRandom(); 028 } 029 }; 030 031 /** 032 * Pseudo-random number generator object for use with randomString(). 033 * The Random class is not considered to be cryptographically secure, so 034 * only use these random Strings for low to medium security applications. 035 */ 036 static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() { 037 @Override 038 protected Random initialValue() { 039 return new Random(); 040 } 041 }; 042 043 public static int nextSecureRandomInt(int bound) { 044 return SECURE_RANDOM.get().nextInt(bound); 045 } 046 047 public static int nextSecureRandomInt() { 048 return SECURE_RANDOM.get().nextInt(); 049 } 050 051 public static void fillWithSecureRandom(byte[] bytes) { 052 SECURE_RANDOM.get().nextBytes(bytes); 053 } 054}