· 7 years ago · Jun 07, 2018, 06:48 AM
1
2///// BOB
3KeyAgreement bobKeyAgree;
4PublicKey alicePubKey;
5SecretKey bobDesKey;
6Cipher bobCipher;
7
8void BTNKHOAACTION(){
9 try{
10 FileInputStream fis = new FileInputStream("D:/A.pub");
11 byte[] akeyP = new byte[fis.available()];
12 fis.read(akeyP);
13 fis.close();
14 txtKhoaA.setText(akeyP.toString());
15
16 }
17 catch(Exception ex){
18
19 }
20}
21
22
23void btnKhoaBAction(){
24 try{
25 boolean read = false;
26 while (!read){
27 try{
28 FileInputStream fis = new FileInputStream("D:/A.pub");
29 fis.close();
30 read = true;
31 }
32 catch(Exception ex){
33
34 }
35 }
36 FileInputStream fis = new FileInputStream("D:/A.pub");
37 byte[] alicePubKeyEnc = new byte[fis.avaiable()];
38 fis.read(alicePubKeyEnc);
39 fis.close();
40 KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
41 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(alicePubKeyEnc);
42 alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
43 DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
44 System.out.println("Generate DH keypair");
45 KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
46 bobKpairGen.initialize(dhParamSpec);
47 KeyPair bobKpair = bobKpairGen.generateKeyPair();
48 System.out.println("Initializing KeyAgreement engine...");
49 bobKeyAgree = KeyAgreement.getInstance("DH");
50 bobKeyAgree.init(bobKpair.getPrivate());
51 byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
52 FileOutputStream fos = new FileOutputStream("D:/B.pub");
53 fos.write(bobPubKeyEnc);
54 fos.close();
55 txtkhoaB.setText(bobPubKeyEnc.toString());
56
57 }
58 catch(Exception ex){
59
60 }
61
62}
63void btnKhoaACtion(){
64 try{
65 bobKeyAgree.doPhase(alicePubKey, true);
66 byte[] bobShareSecret = bobKeyAgree.generateSecret();
67 System.out.println("Khoa chung : Shared secret (DEBUG ONLY : " + CryptoUtil.toGexString(bobShareSecret));
68 txtKhoaChung.setText(CryptoUtil.toHexString(bobSharedSecret));
69 }catch(Exception ex){
70
71 }
72}
73void btnMaKhoa(){
74 try{
75 bobKeyAgree.doPhase(alicePubKey, true);
76 bobDesKey = bobKeyAgree.generateSecret("DES");
77 txtMaHoaKAB.setText(bobDesKey.toString());
78 BufferedWriter bw = null;
79 String fileName = "D:\\KhoaB.txt";
80 bw = new BufferedWriter(new FileWriter(fileName));
81 bw.write(bobDesKey.toString());
82 bw.close();
83 }
84 catch(Exception ex){
85
86 }
87}