Skip to content

Commit 724ddef

Browse files
author
yinyongxiang
committed
添加国密
1 parent c0dcac5 commit 724ddef

File tree

9 files changed

+223
-52
lines changed

9 files changed

+223
-52
lines changed

example/main/java/cn/jpush/api/examples/PushExample.java

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,34 @@
1-
package cn.jpush.api.examples;
2-
3-
import java.net.URI;
4-
import java.net.URISyntaxException;
5-
import java.util.Collection;
6-
import java.util.HashMap;
7-
import java.util.LinkedList;
8-
import java.util.Map;
1+
package main.java.cn.jpush.api.examples;
92

3+
import cn.jiguang.common.ClientConfig;
104
import cn.jiguang.common.ServiceHelper;
115
import cn.jiguang.common.connection.NativeHttpClient;
126
import cn.jiguang.common.connection.NettyHttpClient;
7+
import cn.jiguang.common.resp.APIConnectionException;
8+
import cn.jiguang.common.resp.APIRequestException;
139
import cn.jiguang.common.resp.ResponseWrapper;
10+
import cn.jpush.api.JPushClient;
1411
import cn.jpush.api.push.CIDResult;
1512
import cn.jpush.api.push.GroupPushClient;
13+
import cn.jpush.api.push.PushResult;
14+
import cn.jpush.api.push.model.*;
15+
import cn.jpush.api.push.model.audience.Audience;
16+
import cn.jpush.api.push.model.audience.AudienceTarget;
1617
import cn.jpush.api.push.model.notification.*;
17-
import com.google.gson.*;
18+
import com.google.gson.Gson;
19+
import com.google.gson.GsonBuilder;
20+
import com.google.gson.JsonObject;
21+
import com.google.gson.JsonPrimitive;
1822
import io.netty.handler.codec.http.HttpMethod;
1923
import org.slf4j.Logger;
2024
import org.slf4j.LoggerFactory;
2125

22-
import cn.jiguang.common.ClientConfig;
23-
import cn.jiguang.common.resp.APIConnectionException;
24-
import cn.jiguang.common.resp.APIRequestException;
25-
import cn.jpush.api.JPushClient;
26-
import cn.jpush.api.push.PushResult;
27-
import cn.jpush.api.push.model.Message;
28-
import cn.jpush.api.push.model.Options;
29-
import cn.jpush.api.push.model.Platform;
30-
import cn.jpush.api.push.model.PushPayload;
31-
import cn.jpush.api.push.model.SMS;
32-
import cn.jpush.api.push.model.audience.Audience;
33-
import cn.jpush.api.push.model.audience.AudienceTarget;
26+
import java.net.URI;
27+
import java.net.URISyntaxException;
28+
import java.util.Collection;
29+
import java.util.HashMap;
30+
import java.util.LinkedList;
31+
import java.util.Map;
3432

3533
public class PushExample {
3634
protected static final Logger LOG = LoggerFactory.getLogger(PushExample.class);
@@ -52,10 +50,10 @@ public class PushExample {
5250
public static void main(String[] args) {
5351
// testSendPushWithCustomConfig();
5452
// testSendIosAlert();
55-
testSendPush();
53+
// testSendPush();
5654
// testGetCidList();
5755
// testSendPushes();
58-
// testSendPush_fromJSON();
56+
testSendPush_fromJSON();
5957
// testSendPushWithCallback();
6058
// testSendPushWithCid();
6159
}
@@ -82,6 +80,8 @@ public void onSucceed(ResponseWrapper responseWrapper) {
8280

8381
public static void testSendPush() {
8482
ClientConfig clientConfig = ClientConfig.getInstance();
83+
clientConfig.setPushHostName("http://113.31.136.110:8800");
84+
clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS_TYPE);
8585
final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
8686
// String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
8787
// Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
@@ -118,28 +118,30 @@ public static void testSendPush() {
118118
//use String to build PushPayload instance
119119
public static void testSendPush_fromJSON() {
120120
ClientConfig clientConfig = ClientConfig.getInstance();
121+
clientConfig.setPushHostName("http://113.31.136.110:8800");
122+
clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS_TYPE);
121123
JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
122124
Gson gson = new GsonBuilder()
123125
.registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<PlatformNotification>())
124126
.create();
125127
// Since the type of DeviceType is enum, thus the value should be uppercase, same with the AudienceType.
126-
String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":false,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
128+
String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":true,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
127129
PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
128130
try {
129-
PushResult result = jpushClient.sendPush(payload);
131+
PushResult result = jpushClient.sendPush(payloadString);
130132
LOG.info("Got result - " + result);
131133

132134
} catch (APIConnectionException e) {
133135
LOG.error("Connection error. Should retry later. ", e);
134-
LOG.error("Sendno: " + payload.getSendno());
136+
// LOG.error("Sendno: " + payload.getSendno());
135137

136138
} catch (APIRequestException e) {
137139
LOG.error("Error response from JPush server. Should review and fix it. ", e);
138140
LOG.info("HTTP Status: " + e.getStatus());
139141
LOG.info("Error Code: " + e.getErrorCode());
140142
LOG.info("Error Message: " + e.getErrorMessage());
141143
LOG.info("Msg ID: " + e.getMsgId());
142-
LOG.error("Sendno: " + payload.getSendno());
144+
//LOG.error("Sendno: " + payload.getSendno());
143145
}
144146
}
145147

pom.xml

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
<dependency>
4343
<groupId>cn.jpush.api</groupId>
4444
<artifactId>jiguang-common</artifactId>
45-
<version>1.1.3</version>
45+
<version>1.1.4</version>
4646
</dependency>
4747
<dependency>
4848
<groupId>org.apache.httpcomponents</groupId>
@@ -84,7 +84,19 @@
8484
<scope>test</scope>
8585
</dependency>
8686

87-
<dependency>
87+
<dependency>
88+
<groupId>org.bouncycastle</groupId>
89+
<artifactId>bcprov-jdk15on</artifactId>
90+
<version>1.60</version>
91+
</dependency>
92+
<dependency>
93+
<groupId>org.bouncycastle</groupId>
94+
<artifactId>bcpkix-jdk15on</artifactId>
95+
<version>1.60</version>
96+
</dependency>
97+
98+
99+
<dependency>
88100
<groupId>junit</groupId>
89101
<artifactId>junit</artifactId>
90102
<version>4.11</version>

src/main/java/cn/jpush/api/push/PushClient.java

Lines changed: 79 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
11
package cn.jpush.api.push;
22

3-
import cn.jiguang.common.connection.*;
4-
import com.google.gson.JsonParseException;
5-
import com.google.gson.JsonParser;
6-
73
import cn.jiguang.common.ClientConfig;
84
import cn.jiguang.common.ServiceHelper;
9-
import cn.jiguang.common.utils.Preconditions;
10-
import cn.jiguang.common.utils.StringUtils;
5+
import cn.jiguang.common.connection.*;
116
import cn.jiguang.common.resp.APIConnectionException;
127
import cn.jiguang.common.resp.APIRequestException;
138
import cn.jiguang.common.resp.BaseResult;
149
import cn.jiguang.common.resp.ResponseWrapper;
10+
import cn.jiguang.common.utils.Base64;
11+
import cn.jiguang.common.utils.Preconditions;
12+
import cn.jiguang.common.utils.StringUtils;
13+
import cn.jiguang.common.utils.sm2.SM2Util;
14+
import cn.jpush.api.push.model.EncryptKeys;
15+
import cn.jpush.api.push.model.EncryptPushPayload;
1516
import cn.jpush.api.push.model.PushPayload;
17+
import cn.jpush.api.push.model.audience.Audience;
18+
import com.google.gson.JsonElement;
19+
import com.google.gson.JsonObject;
20+
import com.google.gson.JsonParseException;
21+
import com.google.gson.JsonParser;
1622

1723
/**
1824
* Entrance for sending Push.
@@ -39,6 +45,9 @@ public class PushClient {
3945
// If not present, the default value is 86400(s) (one day)
4046
private long _timeToLive;
4147

48+
// encrypt type, the default value is empty
49+
private String _encryptType;
50+
4251
/**
4352
* Create a Push Client.
4453
*
@@ -96,6 +105,7 @@ public PushClient(String masterSecret, String appKey, HttpProxy proxy, ClientCon
96105

97106
this._apnsProduction = (Integer) conf.get(ClientConfig.APNS_PRODUCTION);
98107
this._timeToLive = (Long) conf.get(ClientConfig.TIME_TO_LIVE);
108+
this._encryptType = (String) conf.get(ClientConfig.ENCRYPT_TYPE);
99109

100110
String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
101111
this._httpClient = new NativeHttpClient(authCode, proxy, conf);
@@ -157,7 +167,7 @@ public PushResult sendPush(PushPayload pushPayload) throws APIConnectionExceptio
157167
pushPayload.resetOptionsTimeToLive(_timeToLive);
158168
}
159169

160-
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushPath, pushPayload.toString());
170+
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushPath, getEncryptData(pushPayload));
161171

162172
return BaseResult.fromResponse(response, PushResult.class);
163173
}
@@ -175,7 +185,7 @@ public PushResult sendPushValidate(PushPayload pushPayload) throws APIConnection
175185
pushPayload.resetOptionsTimeToLive(_timeToLive);
176186
}
177187

178-
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushValidatePath, pushPayload.toString());
188+
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushValidatePath, getEncryptData(pushPayload));
179189

180190
return BaseResult.fromResponse(response, PushResult.class);
181191
}
@@ -189,7 +199,7 @@ public PushResult sendPush(String payloadString) throws APIConnectionException,
189199
Preconditions.checkArgument(false, "payloadString should be a valid JSON string.");
190200
}
191201

192-
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushPath, payloadString);
202+
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushPath, getEncryptData(payloadString));
193203

194204
return BaseResult.fromResponse(response, PushResult.class);
195205
}
@@ -203,7 +213,7 @@ public PushResult sendPushValidate(String payloadString) throws APIConnectionExc
203213
Preconditions.checkArgument(false, "payloadString should be a valid JSON string.");
204214
}
205215

206-
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushValidatePath, payloadString);
216+
ResponseWrapper response = _httpClient.sendPost(_baseUrl + _pushValidatePath, getEncryptData(payloadString));
207217

208218
return BaseResult.fromResponse(response, PushResult.class);
209219
}
@@ -240,6 +250,65 @@ public void close() {
240250
((ApacheHttpClient) _httpClient).close();
241251
}
242252
}
253+
254+
/**
255+
* 获取加密的payload数据
256+
* @param payloadData
257+
* @return
258+
*/
259+
private String getEncryptData(String payloadData) {
260+
JsonElement payloadElement = _jsonParser.parse(payloadData);
261+
JsonObject jsonObject = payloadElement.getAsJsonObject();
262+
Audience audience = Audience.fromJsonElement(jsonObject.get("audience"));
263+
return getEncryptData(payloadData, audience);
264+
}
265+
266+
/**
267+
* 获取加密的payload数据
268+
* @param pushPayload
269+
* @return
270+
*/
271+
private String getEncryptData(PushPayload pushPayload) {
272+
if (_encryptType.isEmpty()) {
273+
return pushPayload.toString();
274+
}
275+
if (EncryptKeys.ENCRYPT_SMS_TYPE.equals(_encryptType)) {
276+
EncryptPushPayload encryptPushPayload = new EncryptPushPayload();
277+
try {
278+
encryptPushPayload.setPayload(String.valueOf(Base64.encode(SM2Util.encrypt(pushPayload.toString(), EncryptKeys.DEFAULT_SM2_ENCRYPT_KEY))));
279+
} catch (Exception e) {
280+
throw new RuntimeException("encrypt word exception", e);
281+
}
282+
encryptPushPayload.setAudience(pushPayload.getAudience());
283+
return encryptPushPayload.toString();
284+
}
285+
// 不支持的加密默认不加密
286+
return pushPayload.toString();
287+
}
288+
289+
/**
290+
* 获取加密的payload数据
291+
* @param pushPayload
292+
* @return
293+
*/
294+
private String getEncryptData(String pushPayload, Audience audience) {
295+
if (_encryptType.isEmpty()) {
296+
return pushPayload;
297+
}
298+
if (EncryptKeys.ENCRYPT_SMS_TYPE.equals(_encryptType)) {
299+
EncryptPushPayload encryptPushPayload = new EncryptPushPayload();
300+
try {
301+
encryptPushPayload.setPayload(String.valueOf(Base64.encode(SM2Util.encrypt(pushPayload, EncryptKeys.DEFAULT_SM2_ENCRYPT_KEY))));
302+
} catch (Exception e) {
303+
throw new RuntimeException("encrypt word exception", e);
304+
}
305+
encryptPushPayload.setAudience(audience);
306+
return encryptPushPayload.toString();
307+
}
308+
// 不支持的加密默认不加密
309+
return pushPayload;
310+
}
311+
243312
}
244313

245314

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package cn.jpush.api.push.model;
2+
3+
public class EncryptKeys {
4+
5+
public static String ENCRYPT_SMS_TYPE = "SM2";
6+
public static String DEFAULT_SM2_ENCRYPT_KEY = "BPj6Mj/T444gxPaHc6CDCizMRp4pEl14WI2lvIbdEK2c+5XiSqmQt2TQc8hMMZqfxcDqUNQW95puAfQx1asv3rU=";
7+
8+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package cn.jpush.api.push.model;
2+
3+
import cn.jpush.api.push.model.audience.Audience;
4+
import com.google.gson.Gson;
5+
import com.google.gson.GsonBuilder;
6+
7+
public class EncryptPushPayload {
8+
9+
private static Gson _gson = new GsonBuilder().disableHtmlEscaping().create();
10+
11+
private String payload;
12+
13+
private Audience audience;
14+
15+
public Audience getAudience() {
16+
return audience;
17+
}
18+
19+
public void setAudience(Audience audience) {
20+
this.audience = audience;
21+
}
22+
23+
public String getPayload() {
24+
return payload;
25+
}
26+
27+
public void setPayload(String payload) {
28+
this.payload = payload;
29+
}
30+
31+
@Override
32+
public String toString() {
33+
return _gson.toJson(this);
34+
}
35+
36+
}

src/main/java/cn/jpush/api/push/model/PushPayload.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,10 @@ public int getSendno() {
132132
}
133133
return 0;
134134
}
135+
136+
public Audience getAudience() {
137+
return audience;
138+
}
135139

136140
@Override
137141
public JsonElement toJSON() {

src/main/java/cn/jpush/api/push/model/audience/Audience.java

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
package cn.jpush.api.push.model.audience;
22

3-
import java.util.Collection;
4-
import java.util.HashSet;
5-
import java.util.Set;
6-
3+
import cn.jiguang.common.utils.Preconditions;
4+
import cn.jpush.api.push.model.PushModel;
75
import com.google.gson.JsonArray;
86
import com.google.gson.JsonElement;
97
import com.google.gson.JsonObject;
108
import com.google.gson.JsonPrimitive;
119

12-
import cn.jiguang.common.utils.Preconditions;
13-
import cn.jpush.api.push.model.PushModel;
10+
import java.util.Collection;
11+
import java.util.HashSet;
12+
import java.util.Set;
1413

1514
public class Audience implements PushModel {
1615
private static final String ALL = "all";
@@ -121,6 +120,22 @@ public JsonElement toJSON() {
121120
return json;
122121
}
123122

123+
public static Audience fromJsonElement(JsonElement jsonElement) {
124+
if (jsonElement == null) {
125+
return null;
126+
}
127+
JsonObject jsonObject = jsonElement.getAsJsonObject();
128+
boolean all = jsonObject.get(ALL).getAsBoolean();
129+
JsonArray jsonArray = jsonObject.getAsJsonArray("targets");
130+
Set<AudienceTarget> audienceTargetSet = new HashSet<>();
131+
if (jsonArray != null) {
132+
for (int i=0; i<jsonArray.size(); i++) {
133+
audienceTargetSet.add(AudienceTarget.fromJsonElement(jsonArray.get(i).getAsJsonObject()));
134+
}
135+
}
136+
return new Audience(all, audienceTargetSet);
137+
}
138+
124139
public static class Builder {
125140
private boolean all = false;
126141
private Set<AudienceTarget> audienceBuilder = null;

0 commit comments

Comments
 (0)