ac906b145321606ba80b9246f1e051deebc10894
[iotcloud.git] / version1 / src / java / iotcloud / CloudComm.java
1 package iotcloud;
2 import java.io.*;
3 import java.net.*;
4 import java.util.Arrays;
5 import javax.crypto.*;
6 import javax.crypto.spec.*;
7 import java.security.SecureRandom;
8
9 /**
10  * This class provides a communication API to the webserver.  It also
11  * validates the HMACs on the slots and handles encryption.
12  * @author Brian Demsky <bdemsky@uci.edu>
13  * @version 1.0
14  */
15
16
17 class CloudComm {
18         String baseurl;
19         Cipher encryptCipher;
20         Cipher decryptCipher;
21         Mac mac;
22         String password;
23         SecureRandom random;
24         static final int SALT_SIZE = 8;
25         byte salt[];
26         Table table;
27         
28         /**
29          * Empty Constructor needed for child class.
30          */
31
32         CloudComm() {
33         }
34
35         /**
36          * Constructor for actual use. Takes in the url and password.
37          */
38
39         CloudComm(Table _table, String _baseurl, String _password) {
40                 this.table=_table;
41                 this.baseurl=_baseurl;
42                 this.password = _password;
43                 this.random = new SecureRandom();
44         }
45
46         /**
47          * Generates Key from password.
48          */
49
50         private SecretKeySpec initKey() {
51                 try {
52                         PBEKeySpec keyspec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
53                         SecretKey tmpkey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(keyspec);
54                         return new SecretKeySpec(tmpkey.getEncoded(), "AES");
55                 } catch (Exception e) {
56                         e.printStackTrace();
57                         throw new Error("Failed generating key.");
58                 }
59         }
60
61         /**
62          * Inits the HMAC generator.
63          */
64
65         private void initCrypt() {
66                 try {
67                         SecretKeySpec key=initKey();
68                         password = null; // drop password
69                         mac = Mac.getInstance("HmacSHA256");
70                         mac.init(key);
71                         encryptCipher =Cipher.getInstance("AES/ECB/PKCS5Padding");
72                         encryptCipher.init(Cipher.ENCRYPT_MODE, key);
73                         decryptCipher =Cipher.getInstance("AES/ECB/PKCS5Padding");
74                         decryptCipher.init(Cipher.DECRYPT_MODE, key);
75                 } catch (Exception e) {
76                         e.printStackTrace();
77                         throw new Error("Failed To Initialize Ciphers");
78                 }
79         }
80
81         /*
82          * Builds the URL for the given request.
83          */
84
85         private URL buildRequest(boolean isput, long sequencenumber, long maxentries) throws IOException {
86                 String reqstring=isput?"req=putslot":"req=getslot";
87                 String urlstr=baseurl+"?"+reqstring+"&seq="+sequencenumber;
88                 if (maxentries != 0)
89                         urlstr += "&max="+maxentries;
90                 return new URL(urlstr);
91         }
92         
93         public void setSalt() {
94                 try {
95                         salt = new byte[SALT_SIZE];
96                         random.nextBytes(salt);
97                         URL url=new URL(baseurl+"?req=setsalt");
98                         URLConnection con=url.openConnection();
99                         HttpURLConnection http = (HttpURLConnection) con;
100                         http.setRequestMethod("POST");
101                         http.setFixedLengthStreamingMode(salt.length);
102                         http.setDoOutput(true);
103                         http.connect();
104                         OutputStream os=http.getOutputStream();
105                         os.write(salt);
106                         int responsecode=http.getResponseCode();
107                         if (responsecode != HttpURLConnection.HTTP_OK)
108                                 throw new Error("Invalid response");
109                 } catch (Exception e) {
110                         e.printStackTrace();
111                         throw new Error("Failed setting salt");
112                 }
113                 initCrypt();
114         }
115
116         private void getSalt() throws Exception {
117                 URL url=new URL(baseurl+"?req=getsalt");
118                 URLConnection con=url.openConnection();
119                 HttpURLConnection http = (HttpURLConnection) con;
120                 http.setRequestMethod("POST");
121                 http.connect();
122                 
123                 InputStream is=http.getInputStream();
124                 DataInputStream dis=new DataInputStream(is);
125                 int salt_length=dis.readInt();
126                 byte [] tmp=new byte[salt_length];
127                 dis.readFully(tmp);
128                 salt=tmp;
129         }
130         
131         /*
132          * API for putting a slot into the queue.  Returns null on success.
133          * On failure, the server will send slots with newer sequence
134          * numbers.
135          */
136
137         Slot[] putSlot(Slot slot, int max) {
138                 try {
139                         if (salt == null) {
140                                 getSalt();
141                                 initCrypt();
142                         }
143                         
144                         long sequencenumber=slot.getSequenceNumber();
145                         byte[] bytes=slot.encode(mac);
146                         bytes = encryptCipher.doFinal(bytes);
147
148                         URL url=buildRequest(true, sequencenumber, max);
149                         URLConnection con=url.openConnection();
150                         HttpURLConnection http = (HttpURLConnection) con;
151
152                         http.setRequestMethod("POST");
153                         http.setFixedLengthStreamingMode(bytes.length);
154                         http.setDoOutput(true);
155                         http.connect();
156
157                         OutputStream os=http.getOutputStream();
158                         os.write(bytes);
159
160                         InputStream is=http.getInputStream();
161                         DataInputStream dis=new DataInputStream(is);
162                         byte[] resptype=new byte[7];
163                         dis.readFully(resptype);
164                         if (Arrays.equals(resptype, "getslot".getBytes()))
165                                 return processSlots(dis);
166                         else if (Arrays.equals(resptype, "putslot".getBytes()))
167                                 return null;
168                         else
169                                 throw new Error("Bad response to putslot");
170                 } catch (Exception e) {
171                         e.printStackTrace();
172                         throw new Error("putSlot failed");
173                 }
174         }
175
176         /**
177          * Request the server to send all slots with the given
178          * sequencenumber or newer.
179          */
180
181         Slot[] getSlots(long sequencenumber) {
182                 try {
183                         if (salt == null) {
184                                 getSalt();
185                                 initCrypt();
186                         }
187                         
188                         URL url=buildRequest(false, sequencenumber, 0);
189                         URLConnection con=url.openConnection();
190                         HttpURLConnection http = (HttpURLConnection) con;
191                         http.setRequestMethod("POST");
192                         http.connect();
193                         InputStream is=http.getInputStream();
194
195                         DataInputStream dis=new DataInputStream(is);
196                         
197                         byte[] resptype=new byte[7];
198                         dis.readFully(resptype);
199                         if (!Arrays.equals(resptype, "getslot".getBytes()))
200                                 throw new Error("Bad Response: "+new String(resptype));
201                         else
202                                 return processSlots(dis);
203                 } catch (Exception e) {
204                         e.printStackTrace();
205                         throw new Error("getSlots failed");
206                 }
207         }
208
209         /**
210          * Method that actually handles building Slot objects from the
211          * server response.  Shared by both putSlot and getSlots.
212          */
213
214         private Slot[] processSlots(DataInputStream dis) throws Exception {
215                 int numberofslots=dis.readInt();
216                 int[] sizesofslots=new int[numberofslots];
217                 Slot[] slots=new Slot[numberofslots];
218                 for(int i=0; i<numberofslots; i++)
219                         sizesofslots[i]=dis.readInt();
220
221                 for(int i=0; i<numberofslots; i++) {
222                         byte[] data=new byte[sizesofslots[i]];
223                         dis.readFully(data);
224
225                         data = decryptCipher.doFinal(data);
226
227                         slots[i]=Slot.decode(table, data, mac);
228                 }
229                 dis.close();
230                 return slots;
231         }
232 }