20165328 實驗五《網絡安全編程》實驗報告

1、網絡編程與安全-1:html

實驗要求:java

  • 參考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA
  • 結對實現中綴表達式轉後綴表達式的功能 MyBc.java
  • 結對實驗從上面功能中獲取的表達式中實現後綴表達式求值的功能,調用MyDc.java

實驗代碼:算法

  • My.Bc:
  • import java.util.*;
    public class MyBC {
        private static LinkedList<String> op1 = new LinkedList<>();
        private static LinkedList<String> op2 = new LinkedList<>();
        private static StringBuilder a = new StringBuilder();
    
        public StringBuilder houzhui(LinkedList<String> list) {
            Iterator<String> i = list.iterator();
            while (i.hasNext()) {
                String s = i.next();
                if (isOperator(s)) {
                    if (op1.isEmpty()) {
                        op1.push(s);
                    } else {
                        if (priority(op1.peek()) <= priority(s) && !s.equals(")")) {
                            op1.push(s);
                        } else if (!s.equals(")") && priority(op1.peek()) > priority(s)) {
                            while (op1.size() != 0 && priority(op1.peek()) >= priority(s)
                                    && !op1.peek().equals("(")) {
                                if (!op1.peek().equals("(")) {
                                    String operator = op1.pop();
                                    a.append(operator).append(" ");
                                    op2.push(operator);
                                }
                            }
                            op1.push(s);
                        } else if (s.equals(")")) {
                            while (!op1.peek().equals("(")) {
                                String operator = op1.pop();
                                a.append(operator).append(" ");
                                op2.push(operator);
                            }
                            op1.pop();
                        }
                    }
                } else {
                    a.append(s).append(" ");
                    op2.push(s);
                }
            }
            if (!op1.isEmpty()) {
                Iterator<String> iterator = op1.iterator();
                while (iterator.hasNext()) {
                    String operator = iterator.next();
                    a.append(operator).append(" ");
                    op2.push(operator);
                    iterator.remove();
                }
            }
            return a;
        }
    
        private static boolean isOperator(String oper) {
            if (oper.equals("+") || oper.equals("-") || oper.equals("/") || oper.equals("*")
                    || oper.equals("(") || oper.equals(")")) {
                return true;
            }
            return false;
        }
    
        private static int priority(String s) {
            switch (s) {
                case "+":
                    return 1;
                case "-":
                    return 1;
                case "*":
                    return 2;
                case "/":
                    return 2;
                case "(":
                    return 3;
                case ")":
                    return 3;
                default:
                    return 0;
            }
        }
    }

     My.Dc:express

  • import java.util.LinkedList;
    import java.util.*;
    
    import java.util.*;
    
    
    
    public class MyDC {
        public static int evaluate(StringBuilder b) {
            LinkedList<String> mList = new LinkedList<>();
            String[] postStr = b.toString().split(" ");
            int result;
            for (String s : postStr) {
                if (fuhao(s)) {
                    if (!mList.isEmpty()) {
                        int num1 = Integer.valueOf(mList.pop());
                        int num2 = Integer.valueOf(mList.pop());
                        if (s.equals("/") && num1 == 0) {
                            System.out.println("除數不能爲0");
                            return 0;
                        }
                        int newNum = cal(num2, num1, s);
                        mList.push(String.valueOf(newNum));
                    }
                } else {
                    mList.push(s);
                }
            }
    
    
            result=Integer.parseInt(mList.pop());
    
            return result;
        }
    
        private static boolean fuhao(String a) {
            if (a.equals("+") || a.equals("-") || a.equals("/") || a.equals("*")
                    || a.equals("(") || a.equals(")")) {
                return true;
            }
            return false;
        }
    
    
        private static int cal(int num1, int num2, String operator) {
            switch (operator) {
                case "+":
                    return num1 + num2;
                case "-":
                    return num1 - num2;
                case "*":
                    return num1 * num2;
                case "/":
                    return num1 / num2;
                default:
                    return 0;
            }
        }
    }

     My.DcTest:編程

  • import java.util.LinkedList;
    import java.util.*;
    
    public class MyDCTest {
        public static void main(String[] args){
            LinkedList<String> list=new LinkedList<>();
            StringBuilder result1;
            int result2;
            String expression, again;
            System.out.println("請輸入一箇中綴表達式並以#結束");
            Scanner scanner=new Scanner(System.in);
            String s;
            while (!(s=scanner.next()).equals("#")) {
                list.add(s);
            }
            MyBC hz=new MyBC();
            result1 = hz.houzhui(list);
            System.out.println("後綴表達式: "+result1);
            MyDC evaluator = new MyDC();
            result2 = evaluator.evaluate(result1);
            System.out.println("That expression equals " + result2);
            System.out.println();
    
        }
    }

實驗截圖:數組

2、網絡安全編程-2:安全

實驗要求服務器

  • 結對編程:1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Scokect實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式用MyBc.java的功能轉化爲後綴表達式,把後綴表達式經過網絡發送給服務器
  • 服務器接收到後綴表達式,調用MyDc.java的功能計算後綴表達式,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試截圖和碼雲連接

實驗代碼:網絡

  • Stack:
  • public class MyStack<T> implements SStack<T> {
        private Object element[];
        private int top;
        public MyStack(int size){
            this.element = new Object[Math.abs(size)];
            this.top = -1;
        }
        public MyStack() {
            this(64);
        }
        public boolean isEmpty() {
            return this.top == -1;
        }
        public void push(T x) {
            if(x==null)
                return;
            if(this.top == element.length-1){
                Object[] temp = this.element;
                this.element = new Object[temp.length*2];
                for(int i = 0; i < temp.length; i++)
                    this.element[i] = temp[i];
            }
            this.top++;
            this.element[this.top] = x;
        }
        public T pop() {
            return this.top==-1 ? null:(T)this.element[this.top--];
        }
        public T get() {
            return this.top==-1 ? null:(T)this.element[this.top];
        }
    }

     SStack:併發

  • public interface SStack<T> {
        boolean isEmpty();
        void push(T x);
        T pop();
        T get();
    }

     Client(客戶端)

  • import java.net.*;
    import java.io.*;
    public class TCPClient {
        public static void main(String srgs[]) {
            try {
                //建立鏈接特定服務器的指定端口的Socket對象
                Socket socket = new Socket("127.0.0.1", 4421);
                //得到從服務器端來的網絡輸入流
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //得到從客戶端向服務器端輸出數據的網絡輸出流
                PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                //建立鍵盤輸入流,以便客戶端從鍵盤上輸入信息
                BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
                System.out.print("請輸入待發送的數據:");
                String str=stdin.readLine(); //從鍵盤讀入待發送的數據
                String postfix = MyBC.toPostfix(str);
                out.println(postfix);  //經過網絡傳送到服務器
                str=in.readLine();//從網絡輸入流讀取結果
                System.out.println( "從服務器接收到的結果爲:"+str); //輸出服務器返回的結果
            }
            catch (Exception e) {
                System.out.println(e);
            }
            finally{
                //stdin.close();
                //in.close();
                //out.close();
                //socket.close();
            }
        }
    }

     Service(服務器):

  • import java.net.*;
    import java.io.*;
    public class TCPServer{
        public static void main(String srgs[]) {
            ServerSocket sc = null;
            Socket socket=null;
            try {
                NewMyDC evaluator = new NewMyDC();
                sc= new ServerSocket(4421);//建立服務器套接字
                System.out.println("端口號:" + sc.getLocalPort());
                System.out.println("服務器已經啓動...");
                socket = sc.accept();   //等待客戶端鏈接
                System.out.println("已經創建鏈接");
                //得到網絡輸入流對象的引用
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                ////得到網絡輸出流對象的引用
                PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                String aline=in.readLine();//讀取客戶端傳送來的數據
                System.out.println("從客戶端接收到信息爲:"+aline); //經過網絡輸出流返回結果給客戶端
                int result = evaluator.value(aline);
                out.println("Echo:" + result);
                out.close();
                in.close();
                sc.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

實驗截圖:

3、網絡編程與安全-3:

實驗要求:

  • 加密結對編程:1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBc.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密後經過網絡把密文發送給服務器
  • 服務器接收到後綴表達式後,進行解密(和客戶端協商密匙,能夠用數組保存)而後調用MyDc.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示服務器發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼:

  • 客服端加密併發送給服務器代碼以下:
  •   KeyGenerator kg = KeyGenerator.getInstance("DESede");
                kg.init(168);
                SecretKey k = kg.generateKey();
                byte[] ptext2 = k.getEncoded();
                Socket socket = new Socket("127.0.0.1", 4421);
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
                //RSA算法,使用服務器端的公鑰對DES的密鑰進行加密
                FileInputStream f3 = new FileInputStream("Skey_RSA_pub.dat");
                ObjectInputStream b2 = new ObjectInputStream(f3);
                RSAPublicKey pbk = (RSAPublicKey) b2.readObject();
                BigInteger e = pbk.getPublicExponent();
                BigInteger n = pbk.getModulus();
                BigInteger m = new BigInteger(ptext2);
                BigInteger c = m.modPow(e, n);
                String cs = c.toString();
                out.println(cs); // 經過網絡將加密後的祕鑰傳送到服務器
                System.out.print("請輸入待發送的數據:");
                //用DES加密明文獲得密文
                String s = stdin.readLine(); // 從鍵盤讀入待發送的數據
                String postfix = MyBC.toPostfix(s);
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE, k);
                byte ptext[] = postfix.getBytes("UTF8");
                byte ctext[] = cp.doFinal(ptext);
                String str = parseByte2HexStr(ctext);
                out.println(str); // 經過網絡將密文傳送到服務器

     服務器解密,計算結果併發送給客戶端代碼以下:

  • String line = in.readLine();
                BigInteger cipher = new BigInteger(line);
                FileInputStream f = new FileInputStream("Skey_RSA_priv.dat");
                ObjectInputStream b = new ObjectInputStream(f);
                RSAPrivateKey prk = (RSAPrivateKey) b.readObject();
                BigInteger d = prk.getPrivateExponent();
                BigInteger n = prk.getModulus();//mod n
                BigInteger m = cipher.modPow(d, n);//m=d (mod n)
                System.out.println("d= " + d);
                System.out.println("n= " + n);
                System.out.println("m= " + m);
                byte[] keykb = m.toByteArray();
                // 使用DES對密文進行解密
                String readline = in.readLine();//讀取客戶端傳送來的數據
                FileInputStream f2 = new FileInputStream("keykb1.dat");
                int num2 = f2.available();
                byte[] ctext = parseHexStr2Byte(readline);
                Key k = new SecretKeySpec(keykb,"DESede");
                Cipher cp = Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                byte[] ptext = cp.doFinal(ctext);
                String p = new String(ptext, "UTF8");//編碼轉換
                System.out.println("從客戶端接收到信息爲:" + p); //打印解密結果
                NewMyDC evaluator = new NewMyDC();
                int _result = evaluator.value(p);
                out.println("Echo:" + _result);
                out.close();
                in.close();
                link.close();

     服務器代碼以下:

  • import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    
    public class SocketService {
        public static void main(String[] args) throws IOException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
            SocketService socketService = new SocketService();
            try {
                socketService.oneServer();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            }
        }
        public  void oneServer() throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            MyDC mydc=new MyDC();
    
            try{
                ServerSocket server=null;
                try{
                    server=new ServerSocket(5204);
                    System.out.println("服務器啓動成功");
                }catch(Exception e) {
                    System.out.println("沒有啓動監聽:"+e);
                }
                Socket socket=null;
                try{
                    socket=server.accept();
                }catch(Exception e) {
                    System.out.println("Error."+e);
                }
                String line;
                BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter writer=new PrintWriter(socket.getOutputStream());
    
                line=in.readLine();
                System.out.printf("密文=%s\n",line);
                // 獲取密鑰
                byte[]ctext=line.getBytes("ISO-8859-1");
                FileInputStream  f2=new FileInputStream("keykb1.dat");
                int num2=f2.available();
                byte[ ] keykb=new byte[num2];
                System.out.printf("\n");
                f2.read(keykb);
                SecretKeySpec k=new  SecretKeySpec(keykb,"DESede");
                // 解密
                Cipher cp=Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                byte []ptext=cp.doFinal(ctext);
                // 顯示明文
    
                String p=new String(ptext,"UTF8");
    
    
    
    
                System.out.println("明文:"+p);
                int a;
                String Np="";
                for(int i=1;i<p.length();i++)
                    Np+=p.charAt(i);
                a=mydc.evaluate(Np);
    
                    writer.println(a);
                    writer.flush();
    
                writer.close();
                in.close();
                socket.close();
                server.close();
            }catch(Exception e) {
                System.out.println("Error."+e);
            }
            // 獲取密文
    
        }
    
    }

     客戶端代碼以下:

  • import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    
    import java.io.*;
    import java.security.*;
    import java.util.Arrays;
    import javax.crypto.*;
    
    public class SocketClient {
        // 搭建客戶端
        public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            MyBC mybc=new MyBC();
            try {
                Socket socket = new Socket("192.168.43.166",5329);
                System.out.println("客戶端啓動成功");
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                PrintWriter write = new PrintWriter(socket.getOutputStream());
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String readline;
                System.out.println("Client:" );
                readline = br.readLine();
                String line=mybc.evaluate(readline);
                FileInputStream f=new FileInputStream("key1.dat");
                ObjectInputStream b=new ObjectInputStream(f);
                Key k=(Key)b.readObject();
                Cipher cp=Cipher.getInstance("DESede");
                cp.init(Cipher.ENCRYPT_MODE, k);
                byte ptext[]=line.getBytes("UTF-8");
    
    
                byte ctext[]=cp.doFinal(ptext);
                String Str=new String(ctext,"ISO-8859-1");
    
                write.println(Str);
                write.flush();
    
    
    
    
    
    
                    System.out.println("Server return:" + in.readLine());
    
                write.close();
                in.close();
                socket.close();
    
            } catch (Exception e) {
                System.out.println("can not listen to:" + e);
            }
    
        }
    
    }

實驗截圖:

4、網絡安全與編程-4:

實驗要求:

  • 密匙分發結對編程:1人負責客戶端,1人負責服務器
  • 注意責任歸宿,要會經過測試證實本身沒問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式用MyBc.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法加密經過網絡把密文發送給服務器
  • 客戶端和服務器用DH算法進行3DES或AES算法的密匙交換
  • 服務器接收到後綴表達式後,進行解密,而後調用MyDc.java的功能計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示發送過來的結果
  • 上傳測試結果截圖和碼雲連接:

實驗代碼:

  • DH公匙代碼以下:
  • public class Key_DH{
        private static final byte skip1024ModulusBytes[] = {
                (byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
                (byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
                (byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
                (byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
                (byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
                (byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
                (byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
                (byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
                (byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
                (byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
                (byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
                (byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
                (byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
                (byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
                (byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
                (byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
                (byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
                (byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
                (byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
                (byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
                (byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
                (byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
                (byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
                (byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
                (byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
                (byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
                (byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
                (byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
                (byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
                (byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
                (byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
                (byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
        };
        // The SKIP 1024 bit modulus
        private static final BigInteger skip1024Modulus
                = new BigInteger(1, skip1024ModulusBytes);
        // The base used with the SKIP 1024 bit modulus
        private static final BigInteger skip1024Base = BigInteger.valueOf(2);
        public static void main(String args[ ]) throws Exception{
            DHParameterSpec DHP=
                    new DHParameterSpec(skip1024Modulus,skip1024Base);
    
            KeyPairGenerator kpg= KeyPairGenerator.getInstance("DH");
            kpg.initialize(DHP);
            KeyPair kp=kpg.genKeyPair();
    
            PublicKey pbk=kp.getPublic();
            PrivateKey prk=kp.getPrivate();
            // 保存公鑰
            FileOutputStream  f1=new FileOutputStream(args[0]);
            ObjectOutputStream b1=new  ObjectOutputStream(f1);
            b1.writeObject(pbk);
            // 保存私鑰
            FileOutputStream  f2=new FileOutputStream(args[1]);
            ObjectOutputStream b2=new  ObjectOutputStream(f2);
            b2.writeObject(prk);
        }
    }

     建立共享密匙:

  • public class KeyAgree{
        public static void main(String args[ ]) throws Exception{
            // 讀取對方的DH公鑰
            FileInputStream f1=new FileInputStream(args[0]);
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
    //讀取本身的DH私鑰
            FileInputStream f2=new FileInputStream(args[1]);
            ObjectInputStream b2=new ObjectInputStream(f2);
            PrivateKey  prk=(PrivateKey)b2.readObject( );
            // 執行密鑰協定
            KeyAgreement ka=KeyAgreement.getInstance("DH");
            ka.init(prk);
            ka.doPhase(pbk,true);
            //生成共享信息
            byte[ ] sb=ka.generateSecret();
            for(int i=0;i<sb.length;i++){
                System.out.print(sb[i]+",");
            }
            SecretKeySpec k=new  SecretKeySpec(sb,"DESede");
        }
    }

實驗截圖:

5、網絡安全編程-5:

實驗要求:

  • 完整性校驗結對編程:1人負責客戶端,1人負責服務器
  • 注意責任歸宿:要會經過測試證實本身沒有問題
  • 基於Java Socket實現客戶端/服務器功能,傳輸方式用TCP
  • 客戶端讓用戶輸入中綴表達式,而後把中綴表達式調用MyBc.java的功能轉化爲後綴表達式,把後綴表達式用3DES或AES算法進行加密經過網絡把密文發送給服務器
  • 客服端和服務器用DH算法進行3DES或AES算法的密匙交換
  • 服務器接收到後綴表達式後進行解密,解密後計算明文的MD5值,和客戶端傳過來的MD5值進行比較,一致則調用MyDc.java算法計算後綴表達式的值,把結果發送給客戶端
  • 客戶端顯示發送過來的結果
  • 上傳測試結果截圖和碼雲連接

實驗代碼:

  • Service:
  • import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    
    public class SocketService {
        public static void main(String[] args) throws IOException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
            SocketService socketService = new SocketService();
            try {
                socketService.oneServer();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            }
        }
        public  void oneServer() throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            MyDC mydc=new MyDC();
    
            try{
                ServerSocket server=null;
                try{
                    server=new ServerSocket(5329);
                    System.out.println("服務器啓動成功");
                }catch(Exception e) {
                    System.out.println("沒有啓動監聽:"+e);
                }
                Socket socket=null;
                try{
                    socket=server.accept();
                }catch(Exception e) {
                    System.out.println("Error."+e);
                }
                String line;
                BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter writer=new PrintWriter(socket.getOutputStream());
    
                line=in.readLine();
                String line1=in.readLine();
                System.out.printf("密文=%s\n",line);
                // 獲取密鑰
                byte[]ctext=line.getBytes("ISO-8859-1");
                FileInputStream  f2=new FileInputStream("keykb1.dat");
                int num2=f2.available();
                byte[ ] keykb=new byte[num2];
                System.out.printf("\n");
                f2.read(keykb);
                SecretKeySpec k=new  SecretKeySpec(keykb,"DESede");
                // 解密
                Cipher cp=Cipher.getInstance("DESede");
                cp.init(Cipher.DECRYPT_MODE, k);
                byte []ptext=cp.doFinal(ctext);
                // 顯示明文
    
                String p=new String(ptext,"UTF8");
    
                int a;
    
    
                System.out.println("明文:"+p);
                String Np="";
                for(int i=1;i<p.length();i++)
                    Np+=p.charAt(i);
                a=mydc.evaluate(Np);
                String x=p;
                MessageDigest m=MessageDigest.getInstance("MD5");
                m.update(x.getBytes("UTF8"));
                byte s[ ]=m.digest( );
                String result="";
                for (int i=0; i<s.length; i++){
                    result+=Integer.toHexString((0x000000ff & s[i]) |
                            0xffffff00).substring(6);
                }
                if(!(line1.equals(result)))System.out.printf("MD5比對正確!\n");
    
                writer.println(a);
                writer.flush();
    
                writer.close();
                in.close();
                socket.close();
                server.close();
            }catch(Exception e) {
                System.out.println("Error."+e);
            }
            // 獲取密文
    
        }

     建立共享密匙:

  • public class KeyAgree{
        public static void main(String args[ ]) throws Exception{
            // 讀取對方的DH公鑰
            FileInputStream f1=new FileInputStream(args[0]);
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
    //讀取本身的DH私鑰
            FileInputStream f2=new FileInputStream(args[1]);
            ObjectInputStream b2=new ObjectInputStream(f2);
            PrivateKey  prk=(PrivateKey)b2.readObject( );
            // 執行密鑰協定
            KeyAgreement ka=KeyAgreement.getInstance("DH");
            ka.init(prk);
            ka.doPhase(pbk,true);
            //生成共享信息
            byte[ ] sb=ka.generateSecret();
            for(int i=0;i<sb.length;i++){
                System.out.print(sb[i]+",");
            }
            SecretKeySpec k=new  SecretKeySpec(sb,"DESede");
        }
    }

實驗截圖:

6、實驗體會:

  • 在最初拿到這個實驗時束手無策,不一樣與以往的實驗,此次實驗沒有現成的教程,一切都須要本身摸索實踐,我和結對夥伴本來準備分開完成客戶端和服務器代碼的,但在實踐編寫後咱們發現單獨編寫對咱們兩的難度太大了,因而咱們兩最終一塊兒編寫了全部的代碼,在此過程當中咱們兩互相啓迪,協同共進,雖然遇到了許多問題,但最終仍是迎刃而解,在這次試驗中,我十分感謝本身的夥伴,他給了許多幫助,也讓我瞭解學習了許多
相關文章
相關標籤/搜索