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  
17  package io.netty.handler.ssl.util;
18  
19  import io.netty.util.internal.PlatformDependent;
20  
21  import java.security.SecureRandom;
22  import java.util.Random;
23  import java.util.concurrent.ThreadLocalRandom;
24  
25  /**
26   * Insecure {@link SecureRandom} which relies on {@link PlatformDependent#threadLocalRandom()} for random number
27   * generation.
28   */
29  final class ThreadLocalInsecureRandom extends SecureRandom {
30  
31      private static final long serialVersionUID = -8209473337192526191L;
32  
33      private static final SecureRandom INSTANCE = new ThreadLocalInsecureRandom();
34  
35      static SecureRandom current() {
36          return INSTANCE;
37      }
38  
39      private ThreadLocalInsecureRandom() { }
40  
41      @Override
42      public String getAlgorithm() {
43          return "insecure";
44      }
45  
46      @Override
47      public void setSeed(byte[] seed) { }
48  
49      @Override
50      public void setSeed(long seed) { }
51  
52      @Override
53      public void nextBytes(byte[] bytes) {
54          random().nextBytes(bytes);
55      }
56  
57      @Override
58      public byte[] generateSeed(int numBytes) {
59          byte[] seed = new byte[numBytes];
60          random().nextBytes(seed);
61          return seed;
62      }
63  
64      @Override
65      public int nextInt() {
66          return random().nextInt();
67      }
68  
69      @Override
70      public int nextInt(int n) {
71          return random().nextInt(n);
72      }
73  
74      @Override
75      public boolean nextBoolean() {
76          return random().nextBoolean();
77      }
78  
79      @Override
80      public long nextLong() {
81          return random().nextLong();
82      }
83  
84      @Override
85      public float nextFloat() {
86          return random().nextFloat();
87      }
88  
89      @Override
90      public double nextDouble() {
91          return random().nextDouble();
92      }
93  
94      @Override
95      public double nextGaussian() {
96          return random().nextGaussian();
97      }
98  
99      private static Random random() {
100         return ThreadLocalRandom.current();
101     }
102 }