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
24 import java.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26
27
28
29
30 final class WebSocketUtil {
31
32 private static final FastThreadLocal<MessageDigest> MD5 = new FastThreadLocal<MessageDigest>() {
33 @Override
34 protected MessageDigest initialValue() throws Exception {
35 try {
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 return MessageDigest.getInstance("SHA1");
51 } catch (NoSuchAlgorithmException e) {
52
53 throw new InternalError("SHA-1 not supported on this platform - Outdated?");
54 }
55 }
56 };
57
58
59
60
61
62
63
64 static byte[] md5(byte[] data) {
65
66 return digest(MD5, data);
67 }
68
69
70
71
72
73
74
75 static byte[] sha1(byte[] data) {
76
77 return digest(SHA1, data);
78 }
79
80 private static byte[] digest(FastThreadLocal<MessageDigest> digestFastThreadLocal, byte[] data) {
81 MessageDigest digest = digestFastThreadLocal.get();
82 digest.reset();
83 return digest.digest(data);
84 }
85
86
87
88
89
90
91
92 static String base64(byte[] data) {
93 ByteBuf encodedData = Unpooled.wrappedBuffer(data);
94 ByteBuf encoded = Base64.encode(encodedData);
95 String encodedString = encoded.toString(CharsetUtil.UTF_8);
96 encoded.release();
97 return encodedString;
98 }
99
100
101
102
103
104
105
106 static byte[] randomBytes(int size) {
107 byte[] bytes = new byte[size];
108
109 for (int index = 0; index < size; index++) {
110 bytes[index] = (byte) randomNumber(0, 255);
111 }
112
113 return bytes;
114 }
115
116
117
118
119
120
121
122
123 static int randomNumber(int minimum, int maximum) {
124 return (int) (Math.random() * maximum + minimum);
125 }
126
127
128
129
130 private WebSocketUtil() {
131
132 }
133 }