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
35
36
37
38 static ChannelBuffer md5(ChannelBuffer buffer) {
39 try {
40 MessageDigest md = MessageDigest.getInstance("MD5");
41 if (buffer.hasArray()) {
42 int offset = buffer.arrayOffset() + buffer.readerIndex();
43 int length = buffer.readableBytes();
44 md.update(buffer.array(), offset, length);
45 } else {
46 md.update(buffer.toByteBuffer());
47 }
48 return ChannelBuffers.wrappedBuffer(md.digest());
49 } catch (NoSuchAlgorithmException e) {
50 throw new InternalError("MD5 not supported on this platform");
51 }
52 }
53
54
55
56
57
58
59
60
61 static ChannelBuffer sha1(ChannelBuffer buffer) {
62 try {
63 MessageDigest md = MessageDigest.getInstance("SHA1");
64 if (buffer.hasArray()) {
65 int offset = buffer.arrayOffset() + buffer.readerIndex();
66 int length = buffer.readableBytes();
67 md.update(buffer.array(), offset, length);
68 } else {
69 md.update(buffer.toByteBuffer());
70 }
71 return ChannelBuffers.wrappedBuffer(md.digest());
72 } catch (NoSuchAlgorithmException e) {
73 throw new InternalError("SHA-1 not supported on this platform");
74 }
75 }
76
77
78
79
80
81
82
83
84 static String base64(ChannelBuffer buffer) {
85 return Base64.encode(buffer).toString(CharsetUtil.UTF_8);
86 }
87
88
89
90
91
92
93
94
95 static byte[] randomBytes(int size) {
96 byte[] bytes = new byte[size];
97
98 for (int i = 0; i < size; i++) {
99 bytes[i] = (byte) randomNumber(0, 255);
100 }
101
102 return bytes;
103 }
104
105
106
107
108
109
110
111
112
113
114 static int randomNumber(int min, int max) {
115 return (int) (Math.random() * max + min);
116 }
117
118 private WebSocketUtil() {
119
120 }
121 }