Skip to content

Commit df0e1f3

Browse files
author
Max Presman
committed
encryption on publish
1 parent 79feb93 commit df0e1f3

7 files changed

Lines changed: 161 additions & 22 deletions

File tree

‎src/main/java/com/pubnub/api/core/Crypto.java‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,33 +16,38 @@
1616
import java.security.NoSuchAlgorithmException;
1717
import java.security.spec.AlgorithmParameterSpec;
1818

19+
20+
1921
@Slf4j
20-
abstract class Crypto {
22+
public class Crypto {
2123

2224
byte[] keyBytes = null;
2325
byte[] ivBytes = null;
24-
String IV = "0123456789012345";
25-
String CIPHER_KEY;
26+
String initializationVector = "0123456789012345";
27+
String cipherKey;
2628
boolean INIT = false;
2729

28-
public Crypto(String CIPHER_KEY) {
29-
this.CIPHER_KEY = CIPHER_KEY;
30+
public Crypto(String cipherKey) {
31+
this.cipherKey = cipherKey;
3032
}
3133

32-
public Crypto(String CIPHER_KEY, String initialization_vector) {
33-
if (initialization_vector != null)
34-
this.IV = initialization_vector;
35-
this.CIPHER_KEY = CIPHER_KEY;
34+
public Crypto(String cipherKey, String customInitializationVector) {
35+
if (customInitializationVector != null) {
36+
this.initializationVector = customInitializationVector;
37+
}
38+
39+
this.cipherKey = cipherKey;
3640
}
3741

3842
public void InitCiphers() throws PubnubException {
3943
if (INIT)
4044
return;
4145
try {
4246

43-
keyBytes = new String(hexEncode(sha256(this.CIPHER_KEY.getBytes("UTF-8"))), "UTF-8").substring(0, 32)
47+
keyBytes = new String(hexEncode(sha256(this.cipherKey.getBytes("UTF-8"))), "UTF-8")
48+
.substring(0, 32)
4449
.toLowerCase().getBytes("UTF-8");
45-
ivBytes = IV.getBytes("UTF-8");
50+
ivBytes = initializationVector.getBytes("UTF-8");
4651
INIT = true;
4752
} catch (UnsupportedEncodingException e) {
4853
throw new PubnubException(newCryptoError(11, e.toString()));
@@ -70,7 +75,7 @@ public String encrypt(String input) throws PubnubException {
7075
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
7176
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
7277
Cipher cipher = null;
73-
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
78+
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
7479
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
7580
return new String(Base64.encode(cipher.doFinal(input.getBytes("UTF-8")), 0));
7681
} catch (NoSuchAlgorithmException e) {
@@ -103,7 +108,7 @@ public String decrypt(String cipher_text) throws PubnubException {
103108
InitCiphers();
104109
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
105110
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
106-
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
111+
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
107112
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
108113
return new String(cipher.doFinal(Base64.decode(cipher_text, 0)), "UTF-8");
109114
} catch (IllegalArgumentException e) {

‎src/main/java/com/pubnub/api/core/Pubnub.java‎

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,73 @@ public final Grant.GrantBuilder grant() {
9494
return Grant.builder().pubnub(this);
9595
}
9696

97-
public GetState.GetStateBuilder getPresenceState() { return GetState.builder().pubnub(this); }
98-
public SetState.SetStateBuilder setPresenceState() { return SetState.builder().pubnub(this).subscriptionManager(subscriptionManager); }
97+
public final GetState.GetStateBuilder getPresenceState() {
98+
return GetState.builder().pubnub(this);
99+
}
100+
public final SetState.SetStateBuilder setPresenceState() {
101+
return SetState.builder().pubnub(this).subscriptionManager(subscriptionManager);
102+
}
103+
104+
public final Publish.PublishBuilder publish() {
105+
return Publish.builder().pubnub(this);
106+
}
99107

100-
public Publish.PublishBuilder publish() { return Publish.builder().pubnub(this); }
108+
// public methods
109+
110+
/**
111+
* Perform Cryptographic decryption of an input string using cipher key provided by PNConfiguration
112+
* @param inputString String to be encrypted
113+
* @return String containing the encryption of inputString using cipherKey
114+
*/
115+
public final String decrypt(String inputString) throws PubnubException {
116+
if (inputString == null) {
117+
throw new PubnubException(PubnubError.PNERROBJ_INVALID_ARGUMENTS);
118+
}
119+
120+
return decrypt(inputString, this.getConfiguration().getCipherKey());
121+
}
122+
123+
/**
124+
* Perform Cryptographic decryption of an input string using the cipher key
125+
* @param inputString String to be encrypted
126+
* @param cipherKey cipher key to be used for encryption
127+
* @throws PubnubException throws exception in case of failed encryption
128+
* @return String containing the encryption of inputString using cipherKey
129+
*/
130+
public final String decrypt(final String inputString, final String cipherKey) throws PubnubException {
131+
if (inputString == null) {
132+
throw new PubnubException(PubnubError.PNERROBJ_INVALID_ARGUMENTS);
133+
}
134+
135+
return new Crypto(cipherKey).decrypt(inputString);
136+
}
137+
138+
/**
139+
* Perform Cryptographic encryption of an input string and the cipher key provided by PNConfiguration
140+
* @param inputString String to be encrypted
141+
* @return String containing the encryption of inputString using cipherKey
142+
*/
143+
public final String encrypt(String inputString) throws PubnubException {
144+
if (inputString == null) {
145+
throw new PubnubException(PubnubError.PNERROBJ_INVALID_ARGUMENTS);
146+
}
147+
148+
return encrypt(inputString, this.getConfiguration().getCipherKey());
149+
}
150+
151+
/**
152+
* Perform Cryptographic encryption of an input string and the cipher key
153+
* @param inputString String to be encrypted
154+
* @param cipherKey cipher key to be used for encryption
155+
* @throws PubnubException throws exception in case of failed encryption
156+
* @return String containing the encryption of inputString using cipherKey
157+
*/
158+
public final String encrypt(final String inputString, final String cipherKey) throws PubnubException {
159+
if (inputString == null) {
160+
throw new PubnubException(PubnubError.PNERROBJ_INVALID_ARGUMENTS);
161+
}
162+
163+
return new Crypto(cipherKey).encrypt(inputString);
164+
}
101165

102166
}

‎src/main/java/com/pubnub/api/endpoints/pubsub/PubSubService.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Call<SubscribeEnvelope> subscribe(@Path("subKey") String subKey,
1818
Call<List<Object>> publish(@Path("pubKey") String pubKey,
1919
@Path("subKey") String subKey,
2020
@Path("channel") String channel,
21-
@Path("message") String message,
21+
@Path("message") Object message,
2222
@QueryMap Map<String, Object> options);
2323

2424
@POST("publish/{pubKey}/{subKey}/0/{channel}/0")

‎src/main/java/com/pubnub/api/endpoints/pubsub/Publish.java‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@
33
import com.fasterxml.jackson.core.JsonProcessingException;
44
import com.fasterxml.jackson.databind.ObjectMapper;
55
import com.fasterxml.jackson.databind.ObjectWriter;
6-
import com.pubnub.api.core.Pubnub;
7-
import com.pubnub.api.core.PubnubError;
8-
import com.pubnub.api.core.PubnubException;
6+
import com.pubnub.api.core.*;
97
import com.pubnub.api.core.enums.PNOperationType;
108
import com.pubnub.api.core.models.PublishData;
119
import com.pubnub.api.endpoints.Endpoint;
@@ -45,6 +43,7 @@ protected final Call<List<Object>> doWork() throws PubnubException {
4543
String stringifiedMessage;
4644
String stringifiedMeta;
4745
ObjectWriter ow = new ObjectMapper().writer();
46+
4847
try {
4948
stringifiedMessage = ow.writeValueAsString(message);
5049
} catch (JsonProcessingException e) {
@@ -70,6 +69,19 @@ protected final Call<List<Object>> doWork() throws PubnubException {
7069
params.put("store", shouldStore);
7170
}
7271

72+
if (pubnub.getConfiguration().getCipherKey() != null) {
73+
Crypto crypto = new Crypto(pubnub.getConfiguration().getCipherKey());
74+
stringifiedMessage = crypto.encrypt(stringifiedMessage);
75+
message = stringifiedMessage;
76+
77+
try {
78+
stringifiedMessage = ow.writeValueAsString(stringifiedMessage);
79+
} catch (JsonProcessingException e) {
80+
throw new PubnubException(PubnubError.PNERROBJ_INVALID_ARGUMENTS, e.getMessage(), null);
81+
}
82+
83+
}
84+
7385
PubSubService service = this.createRetrofit(pubnub).create(PubSubService.class);
7486

7587

‎src/main/java/com/pubnub/api/max_test.java‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import com.pubnub.api.core.models.consumer_facing.PNStatus;
1010
import lombok.extern.slf4j.Slf4j;
1111

12+
import java.util.Arrays;
1213
import java.util.HashMap;
1314
import java.util.Map;
1415

@@ -18,9 +19,10 @@ public class max_test {
1819

1920
public static void main(String[] args) throws InterruptedException, PubnubException {
2021
PnConfiguration pnConfiguration = new PnConfiguration();
21-
pnConfiguration.setSubscribeKey("sub-c-82ab2196-b64f-11e5-8622-0619f8945a4f");
22-
pnConfiguration.setPublishKey("pub-c-8beb3658-0dfd-4032-8f4b-9c6b9ca4d803");
22+
pnConfiguration.setSubscribeKey("sub-c-4cec9f8e-01fa-11e6-8180-0619f8945a4f");
23+
pnConfiguration.setPublishKey("pub-c-d34a0058-6747-4c9d-b669-e651d7e0efb7");
2324
pnConfiguration.setSecretKey("sec-c-NDJkOWM2ZWItNzBhMS00YzllLWFlZjAtNGJlMjVkZjZlNzMy");
25+
pnConfiguration.setCipherKey("testCipher");
2426

2527

2628
Pubnub pubnub = new Pubnub(pnConfiguration);
@@ -52,6 +54,7 @@ public void presence(Pubnub pubnub, PNPresenceEventResult presence) {
5254
// }
5355
//});
5456

57+
/*
5558
try {
5659
Object moose = pubnub.grant().authKey("max")
5760
.channel("ch1-max").channel("ch2-max")
@@ -62,12 +65,18 @@ public void presence(Pubnub pubnub, PNPresenceEventResult presence) {
6265
} catch (PubnubException e) {
6366
e.printStackTrace();
6467
}
68+
*/
6569

70+
pubnub.publish()
71+
.channel("coolChannel").usePOST(true)
72+
.message(Arrays.asList("m1", "m2", "m3")).build().sync();
6673

74+
/*
6775
Object moose = pubnub.audit()
6876
.authKey("max").authKey("max2")
6977
.channel("ch1")
7078
.build().sync();
79+
*/
7180

7281
//Thread.sleep(5000);
7382

‎src/test/java/com.pubnub.api/endpoints/pubsub/PublishTest.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,24 @@ public void testSuccessArraySync() throws PubnubException, InterruptedException
8585
assertEquals("/publish/myPublishKey/mySubscribeKey/0/coolChannel/0/[%22a%22,%22b%22,%22c%22]?uuid=myUUID", server.takeRequest().getPath());
8686
}
8787

88+
@Test
89+
public void testSuccessArrayEncryptedSync() throws PubnubException, InterruptedException {
90+
pubnub.getConfiguration().setCipherKey("testCipher");
91+
server.enqueue(new MockResponse().setBody(("[1,\"Sent\",\"14598111595318003\"]")));
92+
instance.channel("coolChannel").message(Arrays.asList("m1", "m2")).build().sync();
93+
assertEquals("/publish/myPublishKey/mySubscribeKey/0/coolChannel/0/%22HFP7V6bDwBLrwc1t8Rnrog==%5Cn%22?uuid=myUUID", server.takeRequest().getPath());
94+
}
95+
96+
@Test
97+
public void testSuccessPostEncryptedSync() throws PubnubException, InterruptedException {
98+
pubnub.getConfiguration().setCipherKey("testCipher");
99+
server.enqueue(new MockResponse().setBody(("[1,\"Sent\",\"14598111595318003\"]")));
100+
instance.channel("coolChannel").usePOST(true).message(Arrays.asList("m1", "m2")).build().sync();
101+
RecordedRequest recordedRequest = server.takeRequest();
102+
assertEquals("/publish/myPublishKey/mySubscribeKey/0/coolChannel/0?uuid=myUUID", recordedRequest.getPath());
103+
assertEquals("\"HFP7V6bDwBLrwc1t8Rnrog==\\n\"", recordedRequest.getBody().readUtf8().trim());
104+
}
105+
88106
@Test
89107
public void testSuccessHashMapSync() throws PubnubException, InterruptedException {
90108
Map<String, Object> params = new HashMap<String, Object>();

‎src/test/java/com/pubnub/api/PubnubTest.java‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.pubnub.api.core.PubnubException;
66
import org.junit.Assert;
77
import org.junit.Before;
8+
import org.junit.Test;
89

910
import java.io.IOException;
1011

@@ -28,4 +29,34 @@ public void testCreateSuccess() throws IOException, PubnubException {
2829
Assert.assertEquals("https://pubsub.pubnub.com", pubnub.getBaseUrl());
2930
}
3031

32+
@Test
33+
public void testEncryptCustomKey() throws PubnubException {
34+
pubnub = new Pubnub(pnConfiguration);
35+
Assert.assertEquals("iALQtn3PfIXe74CT/wrS7g==", pubnub.encrypt("test1", "cipherKey").trim());
36+
37+
}
38+
39+
@Test
40+
public void testEncryptConfigurationKey() throws PubnubException {
41+
pnConfiguration.setCipherKey("cipherKey");
42+
pubnub = new Pubnub(pnConfiguration);
43+
Assert.assertEquals("iALQtn3PfIXe74CT/wrS7g==", pubnub.encrypt("test1").trim());
44+
45+
}
46+
47+
@Test
48+
public void testDecryptCustomKey() throws PubnubException {
49+
pubnub = new Pubnub(pnConfiguration);
50+
Assert.assertEquals("test1", pubnub.decrypt("iALQtn3PfIXe74CT/wrS7g==", "cipherKey").trim());
51+
52+
}
53+
54+
@Test
55+
public void testDecryptConfigurationKey() throws PubnubException {
56+
pnConfiguration.setCipherKey("cipherKey");
57+
pubnub = new Pubnub(pnConfiguration);
58+
Assert.assertEquals("test1", pubnub.decrypt("iALQtn3PfIXe74CT/wrS7g==").trim());
59+
60+
}
61+
3162
}

0 commit comments

Comments
 (0)