View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty5.handler.ssl.util;
17  
18  import java.security.SecureRandom;
19  import java.util.Random;
20  import java.util.concurrent.ThreadLocalRandom;
21  
22  /**
23   * Insecure {@link SecureRandom} which relies on {@link ThreadLocalRandom#current()} for random number
24   * generation.
25   */
26  final class ThreadLocalInsecureRandom extends SecureRandom {
27  
28      private static final long serialVersionUID = -8209473337192526191L;
29  
30      private static final SecureRandom INSTANCE = new ThreadLocalInsecureRandom();
31  
32      static SecureRandom current() {
33          return INSTANCE;
34      }
35  
36      private ThreadLocalInsecureRandom() { }
37  
38      @Override
39      public String getAlgorithm() {
40          return "insecure";
41      }
42  
43      @Override
44      public void setSeed(byte[] seed) { }
45  
46      @Override
47      public void setSeed(long seed) { }
48  
49      @Override
50      public void nextBytes(byte[] bytes) {
51          random().nextBytes(bytes);
52      }
53  
54      @Override
55      public byte[] generateSeed(int numBytes) {
56          byte[] seed = new byte[numBytes];
57          random().nextBytes(seed);
58          return seed;
59      }
60  
61      @Override
62      public int nextInt() {
63          return random().nextInt();
64      }
65  
66      @Override
67      public int nextInt(int n) {
68          return random().nextInt(n);
69      }
70  
71      @Override
72      public boolean nextBoolean() {
73          return random().nextBoolean();
74      }
75  
76      @Override
77      public long nextLong() {
78          return random().nextLong();
79      }
80  
81      @Override
82      public float nextFloat() {
83          return random().nextFloat();
84      }
85  
86      @Override
87      public double nextDouble() {
88          return random().nextDouble();
89      }
90  
91      @Override
92      public double nextGaussian() {
93          return random().nextGaussian();
94      }
95  
96      private static Random random() {
97          return ThreadLocalRandom.current();
98      }
99  }