1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.http.websocketx;
17
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20
21 import org.jboss.netty.buffer.ChannelBuffer;
22 import org.jboss.netty.buffer.ChannelBuffers;
23 import org.jboss.netty.handler.codec.base64.Base64;
24 import org.jboss.netty.util.CharsetUtil;
25
26
27
28
29 final class WebSocketUtil {
30
31
32
33
34 @Deprecated
35 static byte[] md5(byte[] bytes) {
36 try {
37 MessageDigest md = MessageDigest.getInstance("MD5");
38 return md.digest(bytes);
39 } catch (NoSuchAlgorithmException e) {
40 throw new InternalError("MD5 not supported on this platform");
41 }
42 }
43
44
45
46
47
48
49
50
51 static ChannelBuffer md5(ChannelBuffer buffer) {
52 try {
53 MessageDigest md = MessageDigest.getInstance("MD5");
54 if (buffer.hasArray()) {
55 md.update(buffer.array(), buffer.readerIndex(), buffer.readableBytes());
56 } else {
57 md.update(buffer.toByteBuffer());
58 }
59 return ChannelBuffers.wrappedBuffer(md.digest());
60 } catch (NoSuchAlgorithmException e) {
61 throw new InternalError("MD5 not supported on this platform");
62 }
63 }
64
65
66
67
68 @Deprecated
69 static byte[] sha1(byte[] bytes) {
70 try {
71 MessageDigest md = MessageDigest.getInstance("SHA1");
72 return md.digest(bytes);
73 } catch (NoSuchAlgorithmException e) {
74 throw new InternalError("SHA-1 not supported on this platform");
75 }
76 }
77
78
79
80
81
82
83
84
85 static ChannelBuffer sha1(ChannelBuffer buffer) {
86 try {
87 MessageDigest md = MessageDigest.getInstance("SHA1");
88 if (buffer.hasArray()) {
89 md.update(buffer.array(), buffer.readerIndex(), buffer.readableBytes());
90 } else {
91 md.update(buffer.toByteBuffer());
92 }
93 return ChannelBuffers.wrappedBuffer(md.digest());
94 } catch (NoSuchAlgorithmException e) {
95 throw new InternalError("SHA-1 not supported on this platform");
96 }
97 }
98
99
100
101
102
103 @Deprecated
104 static String base64(byte[] bytes) {
105 ChannelBuffer hashed = ChannelBuffers.wrappedBuffer(bytes);
106 return Base64.encode(hashed).toString(CharsetUtil.UTF_8);
107 }
108
109
110
111
112
113
114
115
116 static String base64(ChannelBuffer buffer) {
117 return Base64.encode(buffer).toString(CharsetUtil.UTF_8);
118 }
119
120
121
122
123
124
125
126
127 static byte[] randomBytes(int size) {
128 byte[] bytes = new byte[size];
129
130 for (int i = 0; i < size; i++) {
131 bytes[i] = (byte) randomNumber(0, 255);
132 }
133
134 return bytes;
135 }
136
137
138
139
140
141
142
143
144
145
146 static int randomNumber(int min, int max) {
147 return (int) (Math.random() * max + min);
148 }
149
150
151 private WebSocketUtil() {
152
153 }
154 }