View Javadoc
1   /*
2    * Copyright 2012 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    *   http://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.netty.handler.codec.http.websocketx;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.Unpooled;
20  import io.netty.handler.codec.base64.Base64;
21  import io.netty.util.CharsetUtil;
22  import io.netty.util.concurrent.FastThreadLocal;
23  import io.netty.util.internal.PlatformDependent;
24  import io.netty.util.internal.SuppressJava6Requirement;
25  
26  import java.security.MessageDigest;
27  import java.security.NoSuchAlgorithmException;
28  
29  /**
30   * A utility class mainly for use by web sockets
31   */
32  final class WebSocketUtil {
33  
34      private static final FastThreadLocal<MessageDigest> MD5 = new FastThreadLocal<MessageDigest>() {
35          @Override
36          protected MessageDigest initialValue() throws Exception {
37              try {
38                  //Try to get a MessageDigest that uses MD5
39                  return MessageDigest.getInstance("MD5");
40              } catch (NoSuchAlgorithmException e) {
41                  //This shouldn't happen! How old is the computer?
42                  throw new InternalError("MD5 not supported on this platform - Outdated?");
43              }
44          }
45      };
46  
47      private static final FastThreadLocal<MessageDigest> SHA1 = new FastThreadLocal<MessageDigest>() {
48          @Override
49          protected MessageDigest initialValue() throws Exception {
50              try {
51                  //Try to get a MessageDigest that uses SHA1
52                  return MessageDigest.getInstance("SHA1");
53              } catch (NoSuchAlgorithmException e) {
54                  //This shouldn't happen! How old is the computer?
55                  throw new InternalError("SHA-1 not supported on this platform - Outdated?");
56              }
57          }
58      };
59  
60      /**
61       * Performs a MD5 hash on the specified data
62       *
63       * @param data The data to hash
64       * @return The hashed data
65       */
66      static byte[] md5(byte[] data) {
67          // TODO(normanmaurer): Create md5 method that not need MessageDigest.
68          return digest(MD5, data);
69      }
70  
71      /**
72       * Performs a SHA-1 hash on the specified data
73       *
74       * @param data The data to hash
75       * @return The hashed data
76       */
77      static byte[] sha1(byte[] data) {
78          // TODO(normanmaurer): Create sha1 method that not need MessageDigest.
79          return digest(SHA1, data);
80      }
81  
82      private static byte[] digest(FastThreadLocal<MessageDigest> digestFastThreadLocal, byte[] data) {
83          MessageDigest digest = digestFastThreadLocal.get();
84          digest.reset();
85          return digest.digest(data);
86      }
87  
88      /**
89       * Performs base64 encoding on the specified data
90       *
91       * @param data The data to encode
92       * @return An encoded string containing the data
93       */
94      @SuppressJava6Requirement(reason = "Guarded with java version check")
95      static String base64(byte[] data) {
96          if (PlatformDependent.javaVersion() >= 8) {
97              return java.util.Base64.getEncoder().encodeToString(data);
98          }
99          String encodedString;
100         ByteBuf encodedData = Unpooled.wrappedBuffer(data);
101         try {
102             ByteBuf encoded = Base64.encode(encodedData);
103             try {
104                 encodedString = encoded.toString(CharsetUtil.UTF_8);
105             } finally {
106                 encoded.release();
107             }
108         } finally {
109             encodedData.release();
110         }
111         return encodedString;
112     }
113 
114     /**
115      * Creates an arbitrary number of random bytes
116      *
117      * @param size the number of random bytes to create
118      * @return An array of random bytes
119      */
120     static byte[] randomBytes(int size) {
121         byte[] bytes = new byte[size];
122         PlatformDependent.threadLocalRandom().nextBytes(bytes);
123         return bytes;
124     }
125 
126     /**
127      * Generates a pseudo-random number
128      *
129      * @param minimum The minimum allowable value
130      * @param maximum The maximum allowable value
131      * @return A pseudo-random number
132      */
133     static int randomNumber(int minimum, int maximum) {
134         assert minimum < maximum;
135         double fraction = PlatformDependent.threadLocalRandom().nextDouble();
136 
137         // the idea here is that nextDouble gives us a random value
138         //
139         //              0 <= fraction <= 1
140         //
141         // the distance from min to max declared as
142         //
143         //              dist = max - min
144         //
145         // satisfies the following
146         //
147         //              min + dist = max
148         //
149         // taking into account
150         //
151         //         0 <= fraction * dist <= dist
152         //
153         // we've got
154         //
155         //       min <= min + fraction * dist <= max
156         return (int) (minimum + fraction * (maximum - minimum));
157     }
158 
159     /**
160      * A private constructor to ensure that instances of this class cannot be made
161      */
162     private WebSocketUtil() {
163         // Unused
164     }
165 }