1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sourceforge.statelessfilter.utils;
17
18 import java.security.SignatureException;
19
20 import javax.servlet.http.Cookie;
21 import javax.servlet.http.HttpServletRequest;
22
23 import org.apache.commons.lang.StringUtils;
24
25
26
27
28
29
30
31 public class CookieUtils {
32
33 private CookieUtils() {
34 }
35
36
37
38
39
40
41
42
43
44
45
46
47 public static Cookie createCookie(String name, String content)
48 throws SignatureException {
49 return createCookie(name, content, null, null, null, false, null);
50 }
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 public static Cookie createCookie(String name, String content,
67 String domain, String path, Integer maxAge)
68 throws SignatureException {
69 return createCookie(name, content, domain, path, maxAge, false, null);
70 }
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88 public static Cookie createCookie(String name, String content,
89 String domain, String path, Integer maxAge, boolean sign, String key)
90 throws SignatureException {
91
92 String cContent = content;
93 if (sign && content != null) {
94 cContent = HmacUtils.signRFC2104HMAC(cContent, key, "|");
95 }
96 Cookie c = new Cookie(name, cContent);
97 if (domain != null) {
98 c.setDomain(domain);
99 }
100
101 if (path != null) {
102 c.setPath(path);
103 }
104
105 if (StringUtils.isEmpty(content)) {
106 c.setMaxAge(0);
107 } else if (maxAge != null) {
108 c.setMaxAge(maxAge.intValue());
109 }
110
111 return c;
112 }
113
114
115
116
117
118
119
120
121
122 public static Cookie getCookie(HttpServletRequest request, String name)
123 throws SignatureException {
124 return getCookie(request, name, false, null);
125 }
126
127
128
129
130
131
132
133
134
135
136
137 public static Cookie getCookie(HttpServletRequest request, String name,
138 boolean sign, String key) throws SignatureException {
139 Cookie[] cookies = request.getCookies();
140 if (cookies != null) {
141 for (int i = cookies.length - 1; i >= 0; i--) {
142 if (name.equals(cookies[i].getName())) {
143 if (sign && cookies[i].getValue() != null) {
144 if (HmacUtils.verifyRFC2104HMAC(cookies[i].getValue(),
145 key, "|") != null) {
146 return cookies[i];
147 }
148 } else {
149 return cookies[i];
150 }
151
152 }
153 }
154 }
155 return null;
156 }
157
158
159
160
161
162
163
164
165 public static String removeCookieSignature(String cookieValue) {
166 if (cookieValue != null && cookieValue.contains("|")) {
167 return cookieValue.split("\\|")[0];
168 }
169
170 return null;
171 }
172 }