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.util.concurrent.FastThreadLocal;
19 import io.netty.util.internal.PlatformDependent;
20
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23 import java.util.Base64;
24
25
26
27
28 final class WebSocketUtil {
29
30 private static final FastThreadLocal<MessageDigest> MD5 = new FastThreadLocal<MessageDigest>() {
31 @Override
32 protected MessageDigest initialValue() throws Exception {
33 try {
34
35
36
37 return MessageDigest.getInstance("MD5");
38 } catch (NoSuchAlgorithmException e) {
39
40 throw new InternalError("MD5 not supported on this platform - Outdated?");
41 }
42 }
43 };
44
45 private static final FastThreadLocal<MessageDigest> SHA1 = new FastThreadLocal<MessageDigest>() {
46 @Override
47 protected MessageDigest initialValue() throws Exception {
48 try {
49
50
51
52 return MessageDigest.getInstance("SHA1");
53 } catch (NoSuchAlgorithmException e) {
54
55 throw new InternalError("SHA-1 not supported on this platform - Outdated?");
56 }
57 }
58 };
59
60
61
62
63
64
65
66 static byte[] md5(byte[] data) {
67
68 return digest(MD5, data);
69 }
70
71
72
73
74
75
76
77 static byte[] sha1(byte[] data) {
78
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
90
91
92
93
94 static String base64(byte[] data) {
95 return Base64.getEncoder().encodeToString(data);
96 }
97
98
99
100
101
102
103
104 static byte[] randomBytes(int size) {
105 byte[] bytes = new byte[size];
106 PlatformDependent.threadLocalRandom().nextBytes(bytes);
107 return bytes;
108 }
109
110
111
112
113
114
115
116
117 static int randomNumber(int minimum, int maximum) {
118 assert minimum < maximum;
119 double fraction = PlatformDependent.threadLocalRandom().nextDouble();
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140 return (int) (minimum + fraction * (maximum - minimum));
141 }
142
143 static int byteAtIndex(int mask, int index) {
144 return (mask >> 8 * (3 - index)) & 0xFF;
145 }
146
147
148
149
150 private WebSocketUtil() {
151
152 }
153 }