KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > protocols > ENCRYPTAsymmetricTest


1 /*
2  * Created on 04-Jul-2004
3  *
4  * To change the template for this generated file go to
5  * Window - Preferences - Java - Code Generation - Code and Comments
6  */

7 package org.jgroups.protocols;
8
9 import junit.framework.TestCase;
10 import org.jgroups.*;
11 import org.jgroups.protocols.ENCRYPT.EncryptHeader;
12 import org.jgroups.stack.Protocol;
13
14 import javax.crypto.Cipher;
15 import java.io.*;
16 import java.security.MessageDigest JavaDoc;
17 import java.security.Security JavaDoc;
18 import java.util.HashMap JavaDoc;
19 import java.util.Map JavaDoc;
20 import java.util.Properties JavaDoc;
21 import java.util.Vector JavaDoc;
22 /**
23  * @author xenephon
24  *
25  * To change the template for this generated type comment go to
26  * Window - Preferences - Java - Code Generation - Code and Comments
27  */

28 public class ENCRYPTAsymmetricTest extends TestCase {
29
30     
31     {
32         Security.addProvider( new org.bouncycastle.jce.provider.BouncyCastleProvider());
33         
34     }
35
36     public void testInitNoProperties()
37     {
38         
39         ENCRYPT encrypt = new ENCRYPT();
40         try {
41             encrypt.init();
42         } catch (Exception JavaDoc e){
43             fail(e.getMessage());
44         }
45         
46         // test the default asymetric key
47
assertEquals("RSA",encrypt.getAsymAlgorithm());
48         assertEquals(512,encrypt.getAsymInit());
49         assertEquals("RSA",encrypt.getKpair().getPublic().getAlgorithm());
50         assertEquals("X.509",encrypt.getKpair().getPublic().getFormat());
51
52         assertNotNull(encrypt.getKpair().getPublic().getEncoded());
53         
54         // test the default symetric key
55
assertEquals("Blowfish",encrypt.getSymAlgorithm());
56         assertEquals(56,encrypt.getSymInit());
57         assertEquals("Blowfish",encrypt.getDesKey().getAlgorithm());
58         assertEquals("RAW",encrypt.getDesKey().getFormat());
59         assertNotNull(encrypt.getDesKey().getEncoded());
60
61         
62         //test the resulting ciphers
63
System.out.println("Provider:"+encrypt.getAsymCipher().getProvider());
64         assertNotNull(encrypt.getAsymCipher());
65         assertNotNull(encrypt.getSymDecodingCipher());
66         assertNotNull(encrypt.getSymEncodingCipher());
67     }
68
69     public void testInitBCAsymProperties()
70     {
71         
72         Properties JavaDoc props = new Properties JavaDoc();
73         props.put("asym_provider","BC");
74         props.put("asym_algorithm","RSA");
75         //javax.
76
ENCRYPT encrypt = new ENCRYPT();
77         encrypt.setProperties(props);
78         try {
79             encrypt.init();
80         } catch (Exception JavaDoc e){
81             fail(e.getMessage());
82         }
83         
84         // test the default asymetric key
85
assertEquals("RSA",encrypt.getAsymAlgorithm());
86         assertEquals(512,encrypt.getAsymInit());
87         assertEquals("RSA",encrypt.getKpair().getPublic().getAlgorithm());
88         //Strangely this returns differently from the default provider for RSA which is also BC!
89
assertEquals("X.509",encrypt.getKpair().getPublic().getFormat());
90         assertNotNull(encrypt.getKpair().getPublic().getEncoded());
91         
92         
93         
94         //test the resulting ciphers
95
assertNotNull(encrypt.getAsymCipher());
96     
97     }
98
99     public void XtestInitRSABlockAsymProperties()
100     {
101         
102         Properties JavaDoc props = new Properties JavaDoc();
103         props.put("asym_algorithm","RSA/ECB/OAEPPadding");
104         //javax.
105
ENCRYPT encrypt = new ENCRYPT();
106         encrypt.setProperties(props);
107         try {
108             encrypt.init();
109         } catch (Exception JavaDoc e){
110             fail(e.getMessage());
111         }
112         
113         // test the default asymetric key
114
assertEquals("RSA/ECB/OAEPPadding",encrypt.getAsymAlgorithm());
115         assertEquals(512,encrypt.getAsymInit());
116         assertEquals("RSA",encrypt.getKpair().getPublic().getAlgorithm());
117         //Strangely this returns differently from the default provider for RSA which is also BC!
118
assertEquals("X509",encrypt.getKpair().getPublic().getFormat());
119         assertNotNull(encrypt.getKpair().getPublic().getEncoded());
120         
121         
122         
123         //test the resulting ciphers
124
assertNotNull(encrypt.getAsymCipher());
125     
126     }
127     
128
129     
130     public void testInitIDEAProperties()
131     {
132         Properties JavaDoc props = new Properties JavaDoc();
133         props.put("sym_algorithm","IDEA");
134         props.put("sym_init","128");
135         
136         ENCRYPT encrypt = new ENCRYPT();
137         encrypt.setProperties(props);
138         try {
139             encrypt.init();
140         } catch (Exception JavaDoc e){
141             fail(e.getMessage());
142         }
143         
144     
145         // test the default symetric key
146
assertEquals("IDEA",encrypt.getSymAlgorithm());
147         assertEquals(128,encrypt.getSymInit());
148         assertEquals("IDEA",encrypt.getDesKey().getAlgorithm());
149         assertEquals("RAW",encrypt.getDesKey().getFormat());
150         assertNotNull(encrypt.getDesKey().getEncoded());
151
152         
153         //test the resulting ciphers
154

155         assertNotNull(encrypt.getSymDecodingCipher());
156         assertNotNull(encrypt.getSymEncodingCipher());
157     }
158     
159     
160     public void testInitAESProperties()
161     {
162         Properties JavaDoc props = new Properties JavaDoc();
163         props.put("sym_algorithm","AES");
164         props.put("sym_init","128");
165         ENCRYPT encrypt = new ENCRYPT();
166         encrypt.setProperties(props);
167         try {
168             encrypt.init();
169         } catch (Exception JavaDoc e){
170             fail(e.getMessage());
171         }
172         
173     
174         // test the default symetric key
175
assertEquals("AES",encrypt.getSymAlgorithm());
176         assertEquals(128,encrypt.getSymInit());
177         assertEquals("AES",encrypt.getDesKey().getAlgorithm());
178         assertEquals("RAW",encrypt.getDesKey().getFormat());
179         assertNotNull(encrypt.getDesKey().getEncoded());
180
181         
182         //test the resulting ciphers
183

184         assertNotNull(encrypt.getSymDecodingCipher());
185         assertNotNull(encrypt.getSymEncodingCipher());
186     }
187
188     public void testViewChangeBecomeKeyserver() throws Exception JavaDoc{
189         // set up the peer
190
ENCRYPT encrypt = new ENCRYPT();
191         try {
192             encrypt.init();
193         } catch (Exception JavaDoc e){
194             fail(e.getMessage());
195         }
196         
197         // set in the observer
198
MockAddress tempAddress = new MockAddress("encrypt");
199         encrypt.setLocal_addr(tempAddress);
200         MockObserver observer = new MockObserver();
201         encrypt.setObserver(observer);
202         
203         // produce encrypted message
204
Cipher cipher = encrypt.getSymEncodingCipher();
205         
206         MessageDigest JavaDoc digest = MessageDigest.getInstance("MD5");
207         digest.reset();
208         digest.update(encrypt.getDesKey().getEncoded());
209          
210         String JavaDoc symVersion = new String JavaDoc(digest.digest(), "UTF-8");
211         
212         encrypt.keyServer = false;
213         Message msg = new Message();
214         msg.setBuffer(cipher.doFinal("hello".getBytes()));
215         msg.putHeader(EncryptHeader.KEY, new EncryptHeader(
216                 EncryptHeader.ENCRYPT, symVersion));
217         
218         Event evt = new Event(Event.MSG,msg);
219
220         //pass in event to encrypt layer
221

222         encrypt.up(evt);
223         
224         // assert that message is queued as we have no key
225
assertTrue(observer.getUpMessages().isEmpty());
226         
227         // send a view change to trigger the become key server
228
// we use the fact that our address is now the controller one
229
Vector JavaDoc tempVector = new Vector JavaDoc();
230         tempVector.add(tempAddress);
231         View tempView = new View(new ViewId(tempAddress,1),tempVector);
232         Event event = new Event(Event.VIEW_CHANGE,tempView);
233         // this should have changed us to the key server
234
encrypt.up(event);
235         
236         // send another encrypted message
237
Message msg2 = new Message();
238         msg2.setBuffer(cipher.doFinal("hello2".getBytes()));
239         msg2.putHeader(EncryptHeader.KEY, new EncryptHeader(
240                 EncryptHeader.ENCRYPT, symVersion));
241         
242         // we should have three messages now in our observer
243
// that are decrypted
244

245         Event evt2 = new Event(Event.MSG,msg2);
246
247         encrypt.up(evt2);
248         assertEquals(3,observer.getUpMessages().size());
249         
250         
251         Event sent = (Event)observer.getUpMessages().get("message1");
252         
253         
254         assertEquals("hello", new String JavaDoc(((Message)sent.getArg()).getBuffer()));
255         
256         sent = (Event)observer.getUpMessages().get("message2");
257         
258         assertEquals("hello2", new String JavaDoc(((Message)sent.getArg()).getBuffer()));
259     
260         
261     }
262
263
264     public void testViewChangeNewKeyServer() throws Exception JavaDoc{
265         // create peer and server
266
ENCRYPT peer = new ENCRYPT();
267         try {
268             peer.init();
269         } catch (Exception JavaDoc e){
270             fail(e.getMessage());
271         }
272         
273         ENCRYPT server = new ENCRYPT();
274         try {
275             server.init();
276         } catch (Exception JavaDoc e){
277             fail(e.getMessage());
278         }
279         
280         // set up server
281
server.keyServer = true;
282         MockObserver serverObserver = new MockObserver();
283         server.setObserver(serverObserver);
284         Address serverAddress =new MockAddress("server");
285         
286         server.setLocal_addr(serverAddress);
287         //set the server up as keyserver
288
Vector JavaDoc serverVector = new Vector JavaDoc();
289         serverVector.add(serverAddress);
290         View tempView = new View(new ViewId(serverAddress,1),serverVector);
291         Event serverEvent = new Event(Event.VIEW_CHANGE,tempView);
292         server.up(serverEvent);
293         
294         // set up peer
295
Address peerAddress =new MockAddress("peer");
296         peer.setLocal_addr(peerAddress);
297         MockObserver peerObserver = new MockObserver();
298         peer.setObserver(peerObserver);
299         peer.keyServer = false;
300         
301         
302         MessageDigest JavaDoc digest = MessageDigest.getInstance("MD5");
303         digest.reset();
304         digest.update(server.getDesKey().getEncoded());
305          
306         String JavaDoc symVersion = new String JavaDoc(digest.digest(), "UTF-8");
307         
308         // encrypt and send an initial message to peer
309
Cipher cipher = server.getSymEncodingCipher();
310         Message msg = new Message();
311         msg.setBuffer(cipher.doFinal("hello".getBytes()));
312         msg.putHeader(EncryptHeader.KEY, new EncryptHeader(
313                 EncryptHeader.ENCRYPT, symVersion));
314         
315         Event evt = new Event(Event.MSG,msg);
316
317         peer.up(evt);
318         //assert that message is queued as we have no key from server
319
assertTrue(peerObserver.getUpMessages().isEmpty());
320         
321         // send a view change where we are not the controller
322

323         
324         // send to peer - which should have peer2 as its key server
325
peer.up(serverEvent);
326         // assert that peer\ keyserver address is now set
327
assertEquals(serverAddress, peer.getKeyServerAddr());
328         
329         // get the resulting message from the peer - should be a key request
330

331         Event sent = (Event)peerObserver.getDownMessages().get("message0");
332
333         assertEquals(((EncryptHeader)((Message)sent.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.KEY_REQUEST);
334         assertEquals(new String JavaDoc(((Message)sent.getArg()).getBuffer()),new String JavaDoc(peer.getKpair().getPublic().getEncoded()));
335         
336         // send this event to server
337
server.up(sent);
338         
339         Event reply = (Event)serverObserver.getDownMessages().get("message1");
340         
341
342         
343         //assert that reply is the session key encrypted with peer's public key
344
assertEquals(((EncryptHeader)((Message)reply.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.SECRETKEY);
345
346     
347         assertNotSame(peer.getDesKey(),server.getDesKey());
348         // now send back to peer
349
peer.up(reply);
350         
351         // assert that both now have same key
352
assertEquals(peer.getDesKey(),server.getDesKey());
353         
354         // send another encrypted message to peer to test queue
355
Message msg2 = new Message();
356         msg2.setBuffer(cipher.doFinal("hello2".getBytes()));
357         msg2.putHeader(EncryptHeader.KEY, new EncryptHeader(
358                 EncryptHeader.ENCRYPT, symVersion));
359         
360         Event evt2 = new Event(Event.MSG,msg2);
361
362         peer.up(evt2);
363         
364         // make sure we have the events now in the up layers
365
assertEquals(3,peerObserver.getUpMessages().size());
366         
367         Event tempEvt = (Event)peerObserver.getUpMessages().get("message2");
368         
369         
370         assertEquals("hello", new String JavaDoc(((Message)tempEvt.getArg()).getBuffer()));
371         
372         tempEvt = (Event)peerObserver.getUpMessages().get("message3");
373         
374         assertEquals("hello2", new String JavaDoc(((Message)tempEvt.getArg()).getBuffer()));
375     
376         
377         
378     }
379
380     
381     public void testViewChangeNewKeyServerNewKey() throws Exception JavaDoc{
382         // create peer and server
383
ENCRYPT peer = new ENCRYPT();
384         try {
385             peer.init();
386         } catch (Exception JavaDoc e){
387             fail(e.getMessage());
388         }
389         
390         ENCRYPT server = new ENCRYPT();
391         try {
392             server.init();
393         } catch (Exception JavaDoc e){
394             fail(e.getMessage());
395         }
396         
397         
398         ENCRYPT peer2 = new ENCRYPT();
399         try {
400             peer2.init();
401         } catch (Exception JavaDoc e){
402             fail(e.getMessage());
403         }
404         
405         // set up server
406
server.keyServer = true;
407         MockObserver serverObserver = new MockObserver();
408         server.setObserver(serverObserver);
409         
410         //set the local address and view change to simulate a started instance
411
Address serverAddress = new MockAddress("server");
412         server.setLocal_addr(serverAddress);
413         
414         // set the server up as keyserver
415
Vector JavaDoc serverVector = new Vector JavaDoc();
416         serverVector.add(serverAddress);
417         View tempView = new View(new ViewId(serverAddress,1),serverVector);
418         Event serverEvent = new Event(Event.VIEW_CHANGE,tempView);
419         server.up(serverEvent);
420         
421         
422         // set up peer as if it has started but not recieved view change
423
Address peerAddress = new MockAddress("peer");
424         peer.setLocal_addr(peerAddress);
425         MockObserver peerObserver = new MockObserver();
426         peer.setObserver(peerObserver);
427         peer.keyServer = false;
428         
429         // set up peer2 with server as key server
430
Address peer2Address = new MockAddress("peer2");
431         peer2.setLocal_addr(peer2Address);
432         MockObserver peer2Observer = new MockObserver();
433         peer2.setObserver(peer2Observer);
434         peer2.keyServer = false;
435         peer2.setKeyServerAddr(serverAddress);
436         
437         // send an encrypted message from the server
438
Message msg = new Message();
439         msg.setBuffer("hello".getBytes());
440         
441         
442         Event evt = new Event(Event.MSG,msg);
443
444         server.down(evt);
445         
446         // message0 is in response to view change
447
Event encEvt = (Event)serverObserver.getDownMessages().get("message1");
448
449         // sent to peer encrypted - should be queued in encyption layer as we do not have a keyserver set
450
peer.up(encEvt);
451         
452         //assert that message is queued as we have no key from server
453
assertTrue(peerObserver.getUpMessages().isEmpty());
454         
455         // send a view change to peer where peer2 is controller
456
Vector JavaDoc peerVector = new Vector JavaDoc();
457         peerVector.add(peer2Address);
458         View tempPeerView = new View(new ViewId(peer2Address,1),peerVector);
459         Event event = new Event(Event.VIEW_CHANGE,tempPeerView);
460         
461         // send to peer - should set peer2 as keyserver
462
peer.up(event);
463         
464         // assert that peer\ keyserver address is now set
465
assertEquals(peer2Address, peer.getKeyServerAddr());
466         
467         // get the resulting message from the peer - should be a key request to peer2
468
Event sent = (Event)peerObserver.getDownMessages().get("message0");
469         
470         // ensure type and that request contains peers pub key
471
assertEquals(((EncryptHeader)((Message)sent.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.KEY_REQUEST);
472         assertEquals(new String JavaDoc(((Message)sent.getArg()).getBuffer()),new String JavaDoc(peer.getKpair().getPublic().getEncoded()));
473         
474         //assume that server is no longer available and peer2 is new server
475
// but did not get the key from server before assuming role
476
// send this event to peer2
477
// send a view change to trigger the become key server
478
// we use the fact that our address is now the controller one
479
// send a view change where we are not the controller
480
Vector JavaDoc peer2Vector = new Vector JavaDoc();
481         peer2Vector.add(peer2Address);
482         View tempPeer2View = new View(new ViewId(peer2Address,1),peer2Vector);
483         Event event2 = new Event(Event.VIEW_CHANGE,tempPeer2View);
484         // this should have changed us to the key server
485
peer2.up(event2);
486         
487         peer2.up(sent);
488         
489         Event reply = (Event)peer2Observer.getDownMessages().get("message1");
490         
491
492         
493         //assert that reply is the session key encrypted with peer's public key
494
assertEquals(((EncryptHeader)((Message)reply.getArg()).getHeader(EncryptHeader.KEY)).getType(), EncryptHeader.SECRETKEY);
495
496     
497         assertNotSame(peer.getDesKey(),peer2.getDesKey());
498         assertNotSame(server.getDesKey(),peer2.getDesKey());
499         
500         // now send back to peer
501
peer.up(reply);
502         
503         // assert that both now have same key
504
assertEquals(peer.getDesKey(),peer2.getDesKey());
505         assertNotSame(server.getDesKey(),peer.getDesKey());
506         
507         
508         // send another encrypted message to peer to test queue
509
Message msg2 = new Message();
510         msg2.setBuffer("hello2".getBytes());
511
512         
513         Event evt2 = new Event(Event.MSG,msg2);
514
515         peer2.down(evt2);
516         
517         Event Evt2 = (Event)peer2Observer.getDownMessages().get("message2");
518
519         peer.up(Evt2);
520         // make sure we have the events now in the up layers
521
assertEquals(2,peerObserver.getUpMessages().size());
522         
523         Event tempEvt = (Event)peerObserver.getUpMessages().get("message2");
524         
525         
526         assertEquals("hello2", new String JavaDoc(((Message)tempEvt.getArg()).getBuffer()));
527         
528
529         
530         
531     }
532
533     
534
535     static class MockObserver implements ENCRYPT.Observer {
536
537         private Map JavaDoc upMessages = new HashMap JavaDoc();
538         private Map JavaDoc downMessages = new HashMap JavaDoc();
539         private int counter =0;
540         /* (non-Javadoc)
541          * @see org.jgroups.UpHandler#up(org.jgroups.Event)
542          */

543         
544         private void storeUp(Event evt){
545             upMessages.put("message"+counter++,evt);
546         }
547         
548         private void storeDown(Event evt){
549             downMessages.put("message"+counter++,evt);
550         }
551         public void up(Event evt)
552         {
553             storeUp(evt);
554             System.out.println("Up:"+evt.toString());
555         }
556
557         /* (non-Javadoc)
558          * @see org.jgroups.stack.ProtocolObserver#setProtocol(org.jgroups.stack.Protocol)
559          */

560         public void setProtocol(Protocol prot)
561         {
562         }
563
564
565
566         /* (non-Javadoc)
567          * @see org.jgroups.stack.ProtocolObserver#up_prot.up(org.jgroups.Event)
568          */

569         public void passUp(Event evt)
570         {
571             storeUp(evt);
572             System.out.println("PassUp:"+evt.toString());
573         }
574
575         /* (non-Javadoc)
576          * @see org.jgroups.stack.ProtocolObserver#down(org.jgroups.Event, int)
577          */

578         public void down(Event evt)
579         {
580             System.out.println("down:"+evt.toString());
581         }
582
583         /* (non-Javadoc)
584          * @see org.jgroups.stack.ProtocolObserver#down_prot.down(org.jgroups.Event)
585          */

586         public void passDown(Event evt)
587         {
588             storeDown(evt);
589             System.out.println("passDown:"+evt.toString());
590         }
591         
592         /**
593          * @return Returns the upMessages.
594          */

595         protected Map JavaDoc getUpMessages()
596         {
597             return upMessages;
598         }
599         /**
600          * @param upMessages The upMessages to set.
601          */

602         protected void setUpMessages(Map JavaDoc upMessages)
603         {
604             this.upMessages = upMessages;
605         }
606         /**
607          * @return Returns the downMessages.
608          */

609         protected Map JavaDoc getDownMessages()
610         {
611             return downMessages;
612         }
613         /**
614          * @param downMessages The downMessages to set.
615          */

616         protected void setDownMessages(Map JavaDoc downMessages)
617         {
618             this.downMessages = downMessages;
619         }
620     }
621     
622     class MockAddress implements Address{
623
624         private static final long serialVersionUID = -479331506050129599L;
625         
626         /* (non-Javadoc)
627          * @see org.jgroups.Address#isMulticastAddress()
628          */

629         String JavaDoc name;
630         public MockAddress(String JavaDoc name){
631             this.name = name;
632         }
633
634         public MockAddress() {
635         }
636
637         public boolean isMulticastAddress()
638         {
639             return false;
640         }
641
642         public int size() {
643             return 0;
644         }
645
646         /* (non-Javadoc)
647          * @see java.io.Externalizable#readExternal(java.io.ObjectInput)
648          */

649         public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException JavaDoc
650         {
651         }
652
653         /* (non-Javadoc)
654          * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput)
655          */

656         public void writeExternal(ObjectOutput out) throws IOException
657         {
658         }
659
660
661
662         /* (non-Javadoc)
663          * @see java.lang.Comparable#compareTo(java.lang.Object)
664          */

665         public int compareTo(Object JavaDoc o)
666         {
667             return -1;
668         }
669         
670         public boolean equals(Object JavaDoc obj){
671             MockAddress address = (MockAddress)obj;
672             return address.name.equals(this.name);
673         }
674
675         public void writeTo(DataOutputStream out) throws IOException {
676         }
677
678         public void readFrom(DataInputStream in) throws IOException, IllegalAccessException JavaDoc, InstantiationException JavaDoc {
679         }
680     }
681
682     
683 }
684
Popular Tags