1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
39
40
41 return MessageDigest.getInstance("MD5");
42 } catch (NoSuchAlgorithmException e) {
43
44 throw new InternalError("MD5 not supported on this platform - Outdated?");
45 }
46 }
47 };
48
49 private static final FastThreadLocal<MessageDigest> SHA1 = new FastThreadLocal<MessageDigest>() {
50 @Override
51 protected MessageDigest initialValue() throws Exception {
52 try {
53
54
55
56 return MessageDigest.getInstance("SHA1");
57 } catch (NoSuchAlgorithmException e) {
58
59 throw new InternalError("SHA-1 not supported on this platform - Outdated?");
60 }
61 }
62 };
63
64
65
66
67
68
69
70 static byte[] md5(byte[] data) {
71
72 return digest(MD5, data);
73 }
74
75
76
77
78
79
80
81 static byte[] sha1(byte[] data) {
82
83 return digest(SHA1, data);
84 }
85
86 private static byte[] digest(FastThreadLocal<MessageDigest> digestFastThreadLocal, byte[] data) {
87 MessageDigest digest = digestFastThreadLocal.get();
88 digest.reset();
89 return digest.digest(data);
90 }
91
92
93
94
95
96
97
98 @SuppressJava6Requirement(reason = "Guarded with java version check")
99 static String base64(byte[] data) {
100 if (PlatformDependent.javaVersion() >= 8) {
101 return java.util.Base64.getEncoder().encodeToString(data);
102 }
103 String encodedString;
104 ByteBuf encodedData = Unpooled.wrappedBuffer(data);
105 try {
106 ByteBuf encoded = Base64.encode(encodedData);
107 try {
108 encodedString = encoded.toString(CharsetUtil.UTF_8);
109 } finally {
110 encoded.release();
111 }
112 } finally {
113 encodedData.release();
114 }
115 return encodedString;
116 }
117
118
119
120
121
122
123
124 static byte[] randomBytes(int size) {
125 byte[] bytes = new byte[size];
126 PlatformDependent.threadLocalRandom().nextBytes(bytes);
127 return bytes;
128 }
129
130
131
132
133
134
135
136
137 static int randomNumber(int minimum, int maximum) {
138 assert minimum < maximum;
139 double fraction = PlatformDependent.threadLocalRandom().nextDouble();
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160 return (int) (minimum + fraction * (maximum - minimum));
161 }
162
163 static int byteAtIndex(int mask, int index) {
164 return (mask >> 8 * (3 - index)) & 0xFF;
165 }
166
167
168
169
170 private WebSocketUtil() {
171
172 }
173 }