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