KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > test > DHKeyAgreementTest


1 package net.sourceforge.jcetaglib.test;
2
3 import junit.framework.Assert;
4 import junit.framework.TestCase;
5 import net.sourceforge.jcetaglib.lib.Crypt;
6 import net.sourceforge.jcetaglib.lib.DHKeyAgreement;
7
8 import java.security.Key JavaDoc;
9 import java.security.KeyPair JavaDoc;
10 import java.security.PublicKey JavaDoc;
11
12 public class DHKeyAgreementTest extends TestCase {
13     private StringBuffer JavaDoc ciphertext = null;
14     private StringBuffer JavaDoc plaintext = null;
15
16     public void testAgreement() throws Exception JavaDoc {
17         // generate key pairs for both parties
18
KeyPair JavaDoc alicekeypair = DHKeyAgreement.generateDHKeyPair();
19         KeyPair JavaDoc bobkeypair = DHKeyAgreement.generateDHKeyPair();
20
21         // public key wrapping
22
byte[] bytealicekey = DHKeyAgreement.publicKeyToBytes(alicekeypair.getPublic()); // send this to Bob
23
byte[] bytebobkey = DHKeyAgreement.publicKeyToBytes(bobkeypair.getPublic()); // send this to Alice
24

25         // receiving public keys ...
26
PublicKey JavaDoc alicepub = DHKeyAgreement.bytesToPublicKey(bytealicekey);
27         PublicKey JavaDoc bobpub = DHKeyAgreement.bytesToPublicKey(bytebobkey);
28
29         // generate secret session keys for both parties
30
Key JavaDoc alicekey = DHKeyAgreement.generateSessionKey(bobpub, alicekeypair.getPrivate(), "AES", 256);
31         Key JavaDoc bobkey = DHKeyAgreement.generateSessionKey(alicepub, bobkeypair.getPrivate(), "AES", 256);
32
33         Assert.assertEquals(alicekey, bobkey);
34
35         for (int i = 0; i < RunTest.text.length; i++) {
36             // alice encrypts it with her key
37
ciphertext = Crypt.encrypt(RunTest.text[i]
38                     , alicekey
39                     , "AES"
40                     , "CBC"
41                     , "PKCS7Padding"
42                     , null);
43
44             // bob decrypts it with his key
45
plaintext = Crypt.decrypt(ciphertext
46                     , bobkey
47                     , "AES"
48                     , "CBC"
49                     , "PKCS7Padding");
50
51             Assert.assertEquals(plaintext.toString(), RunTest.text[i].toString());
52         }
53     }
54 }
55
Popular Tags