RandomUtil.java

  1. /**
  2.  *
  3.  * Copyright 2003-2007 Jive Software, 2016-2021 Florian Schmaus.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.util;

  18. import java.security.SecureRandom;
  19. import java.util.Random;

  20. public class RandomUtil {

  21.     static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>() {
  22.         @Override
  23.         protected SecureRandom initialValue() {
  24.             return new SecureRandom();
  25.         }
  26.     };

  27.     /**
  28.      * Pseudo-random number generator object for use with randomString().
  29.      * The Random class is not considered to be cryptographically secure, so
  30.      * only use these random Strings for low to medium security applications.
  31.      */
  32.     static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() {
  33.         @Override
  34.         protected Random initialValue() {
  35.             return new Random();
  36.         }
  37.     };

  38.     public static int nextSecureRandomInt(int bound) {
  39.         return SECURE_RANDOM.get().nextInt(bound);
  40.     }

  41.     public static int nextSecureRandomInt() {
  42.         return SECURE_RANDOM.get().nextInt();
  43.     }

  44.     public static void fillWithSecureRandom(byte[] bytes) {
  45.         SECURE_RANDOM.get().nextBytes(bytes);
  46.     }
  47. }