forked from ringcentral/pubnub-jtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPubNubUtil.java
More file actions
199 lines (161 loc) · 6.25 KB
/
Copy pathPubNubUtil.java
File metadata and controls
199 lines (161 loc) · 6.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package com.pubnub.api;
import com.pubnub.api.builder.PubNubErrorBuilder;
import com.pubnub.api.vendor.Base64;
import lombok.extern.java.Log;
import okhttp3.HttpUrl;
import okhttp3.Request;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
@Log
public class PubNubUtil {
private PubNubUtil() {
}
public static String joinString(List<String> val, String delim) {
StringBuilder builder = new StringBuilder();
for (String l : val) {
builder.append(l);
builder.append(",");
}
return builder.toString().substring(0, builder.toString().length() - 1);
}
public static String joinLong(List<Long> val, String delim) {
StringBuilder builder = new StringBuilder();
for (Long l : val) {
builder.append(Long.toString(l).toLowerCase());
builder.append(",");
}
return builder.toString().substring(0, builder.toString().length() - 1);
}
/**
* Returns encoded String
*
* @param stringToEncode , input string
* @return , encoded string
*/
public static String pamEncode(String stringToEncode) {
/* !'()*~ */
String encoded = urlEncode(stringToEncode);
if (encoded != null) {
encoded = encoded
.replace("*", "%2A")
.replace("!", "%21")
.replace("'", "%27")
.replace("(", "%28")
.replace(")", "%29")
.replace("[", "%5B")
.replace("]", "%5D")
.replace("~", "%7E");
}
return encoded;
}
/**
* Returns encoded String
*
* @param stringToEncode , input string
* @return , encoded string
*/
public static String urlEncode(String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, "UTF-8").replace("+", "%20");
} catch (UnsupportedEncodingException e) {
return null;
}
}
/**
* Returns decoded String
*
* @param stringToEncode , input string
* @return , decoded string
*/
public static String urlDecode(String stringToEncode) {
try {
return URLDecoder.decode(stringToEncode, "UTF-8");
} catch (UnsupportedEncodingException e) {
return null;
}
}
public static String preparePamArguments(Map<String, String> pamArgs) {
Set<String> pamKeys = new TreeSet(pamArgs.keySet());
String stringifiedArguments = "";
int i = 0;
for (String pamKey : pamKeys) {
if (i != 0) {
stringifiedArguments = stringifiedArguments.concat("&");
}
stringifiedArguments =
stringifiedArguments.concat(pamKey).concat("=").concat(pamEncode(pamArgs.get(pamKey)));
i += 1;
}
return stringifiedArguments;
}
public static String signSHA256(String key, String data) throws PubNubException {
Mac sha256HMAC;
byte[] hmacData;
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), "HmacSHA256");
try {
sha256HMAC = Mac.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build();
}
try {
sha256HMAC.init(secretKey);
} catch (InvalidKeyException e) {
throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build();
}
try {
hmacData = sha256HMAC.doFinal(data.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw PubNubException.builder().pubnubError(PubNubErrorBuilder.PNERROBJ_CRYPTO_ERROR).errormsg(e.getMessage()).build();
}
return new String(Base64.encode(hmacData, 0), Charset.forName("UTF-8")).replace('+', '-').replace('/', '_').replace("\n", "");
}
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos).concat(replacement).concat(string.substring(pos + toReplace.length(),
string.length()));
} else {
return string;
}
}
public static Request requestSigner(Request originalRequest, PNConfiguration pnConfiguration, int timestamp) {
// only sign if we have a secret key in place.
if (pnConfiguration.getSecretKey() == null) {
return originalRequest;
}
HttpUrl url = originalRequest.url();
String requestURL = url.encodedPath();
Map<String, String> queryParams = new HashMap<>();
String signature = "";
for (String queryKey : url.queryParameterNames()) {
queryParams.put(queryKey, url.queryParameter(queryKey));
}
queryParams.put("timestamp", String.valueOf(timestamp));
String signInput = pnConfiguration.getSubscribeKey() + "\n" + pnConfiguration.getPublishKey() + "\n";
if (requestURL.startsWith("/v1/auth/audit")) {
signInput += "audit" + "\n";
} else if (requestURL.startsWith("/v1/auth/grant")) {
signInput += "grant" + "\n";
} else {
signInput += requestURL + "\n";
}
signInput += PubNubUtil.preparePamArguments(queryParams);
try {
signature = PubNubUtil.signSHA256(pnConfiguration.getSecretKey(), signInput);
} catch (PubNubException e) {
log.warning("signature failed on SignatureInterceptor: " + e.toString());
}
HttpUrl rebuiltUrl = url.newBuilder()
.addQueryParameter("timestamp", String.valueOf(timestamp))
.addQueryParameter("signature", signature)
.build();
return originalRequest.newBuilder().url(rebuiltUrl).build();
}
}