棧:棧 (Stack)是一種只容許在表尾插入和刪除的線性表,有先進後出(FILO),後進先出(LIFO)的特色。容許插入和刪除的一端稱爲棧頂(top),另外一端稱爲棧底(bottom)。html
表達式Exp = S1 + OP + S2
有三種標識方法,例子(a * b + (c - d / e) * f):java
dc計算後綴表達式:算法
MyDC:express
import java.util.StringTokenizer; import java.util.Stack; public class MyDC { private final char ADD = '+'; private final char SUBTRACT = '-'; private final char MULTIPLY = '*'; private final char DIVIDE = '/'; private Stack<Integer> stack; public MyDC() { stack = new Stack<Integer>(); } public int evaluate(String expr) { int op1, op2, result = 0; String token; StringTokenizer tokenizer = new StringTokenizer(expr); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (isOperator(token)) { op2 = (stack.pop()).intValue(); op1 = (stack.pop()).intValue(); result = evalSingleOp(token.charAt(0), op1, op2); stack.push(new Integer(result)); } else stack.push(new Integer(Integer.parseInt(token))); } return result; } private boolean isOperator(String token) { return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")); } private int evalSingleOp(char operation, int op1, int op2) { int result = 0; switch (operation) { case ADD: result = op1 + op2; break; case SUBTRACT: result = op1 - op2; break; case MULTIPLY: result = op1 * op2; break; case DIVIDE: result = op1 / op2; } return result; } }
MyDCTest:編程
import java.util.Scanner; public class MyDCTest { public static void main (String[] args) { String expression, again; int result; try { Scanner in = new Scanner(System.in); do { MyDC evaluator = new MyDC(); System.out.println ("Enter a valid postfix expression: "); expression = in.nextLine(); result = evaluator.evaluate (expression); System.out.println(); System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? "); again = in.nextLine(); System.out.println(); } while (again.equalsIgnoreCase("y")); } catch (Exception IOException) { System.out.println("Input exception reported"); } } }
MyBC:數組
import java.io.IOException; import java.util.Scanner; public class MyBC { private Stack theStack; private String input; private String output = ""; public MyBC(String in) { input = in; int stackSize = input.length(); theStack = new Stack(stackSize); } public String doTrans() { for (int j = 0; j < input.length(); j++) { char ch = input.charAt(j); switch (ch) { case '+': case '-': gotOper(ch, 1); break; case '*': case '/': gotOper(ch, 2); break; case '(': theStack.push(ch); break; case ')': gotParen(ch); break; default: output = output + ch; break; } } while (!theStack.isEmpty()) { output = output + theStack.pop(); } System.out.println(output); return output; } public void gotOper(char opThis, int prec1) { while (!theStack.isEmpty()) { char opTop = theStack.pop(); if (opTop == '(') { theStack.push(opTop); break; } else { int prec2; if (opTop == '+' || opTop == '-') prec2 = 1; else prec2 = 2; if (prec2 < prec1) { theStack.push(opTop); break; } else output = output + opTop; } } theStack.push(opThis); } public void gotParen(char ch){ while (!theStack.isEmpty()) { char chx = theStack.pop(); if (chx == '(') break; else output = output + chx; } } public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); String input = in.nextLine(); System.out.println(input); String output; MyBC theTrans = new MyBC(input); output = theTrans.doTrans(); } class Stack { private int maxSize; private char[] stackArray; private int top; public Stack(int max) { maxSize = max; stackArray = new char[maxSize]; top = -1; } public void push(char j) { stackArray[++top] = j; } public char pop() { return stackArray[top--]; } public char peek() { return stackArray[top]; } public boolean isEmpty() { return (top == -1); } } }
1人負責客戶端,一人負責服務器安全
在編寫客戶端和服務器端以前,回顧了一下對網絡方面的知識的學習:服務器
客戶端程序使用Socket類創建負責鏈接到服務器的套接字對象。網絡
Socket的構造方法是Socket(String host,int port),host是服務器的IP地址,port是一個端口號。創建套接字對象可能發生IOException異常。socket
try{ Socket clientSocket=new Socket("http://192.168.0.78",2010); }catch{}
當前套接字對象clientSocket創建後,clientSocket可使用方法getIntStream()得到一個輸出流,這個輸入流的源和服務器端的一個輸出流的目的地恰好相同,所以客戶端用輸入流能夠讀取服務器寫入到輸出流中的數據;clientSocket使用方法getOutputStream()得到一個輸出流,這個輸出流的目的地和服務器端的一個輸入流的源恰好相同,所以服務器能夠用輸入流能夠讀取客戶寫入到輸出流中的數據。
爲了使客戶成功地鏈接到服務器,服務器必須創建一個ServerSocket對象。
ServerSocket的構造方法是ServerSocket(int port),其中端口號port,必須與客戶呼叫的端口號一致。
服務器端代碼:Server
import java.io.*; import java.net.*; import static java.lang.Integer.*; public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; OutputStream os = null; InputStream is = null; int port = 8087; try { serverSocket = new ServerSocket(port); System.out.println("創建鏈接成功!"); socket = serverSocket.accept(); System.out.println("得到鏈接成功!"); is = socket.getInputStream(); byte[] b = new byte[1024]; int n = is.read(b); System.out.println("接收數據成功!"); String message=new String(b,0,n); System.out.println("來自客戶端的數據內容爲:" + message); String output; MyBC theTrans = new MyBC(message); output = theTrans.doTrans(); os = socket.getOutputStream(); os.write(output.getBytes()); } catch (Exception e) { e.printStackTrace(); }finally{ try{ os.close(); is.close(); socket.close(); serverSocket.close(); }catch(Exception e){} } } }
客戶端代碼:Client
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { Socket socket = null; InputStream is = null; OutputStream os = null; String serverIP = "172.16.252.50"; int port = 8087; System.out.println("輸入中綴表達式:20-16/4+52-11*2"); String output; MyBC theTrans = new MyBC("20-16/4+52-11*2"); output = theTrans.doTrans(); try { socket = new Socket(serverIP, port); System.out.println("創建鏈接成功!"); os = socket.getOutputStream(); os.write(output.getBytes()); System.out.println("發送數據成功!"); is = socket.getInputStream(); byte[] b = new byte[1024]; int n = is.read(b); System.out.println("接收數據成功!"); System.out.println("來自服務器的數據內容爲:" + new String(b, 0, n)); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); os.close(); socket.close(); } catch (Exception e2) { } } } }
1人負責客戶端,一人負責服務器
(1) 獲取密鑰生成器
KeyGenerator kg=KeyGenerator.getInstance("DESede");
(2) 初始化密鑰生成器
kg.init(168);
(3) 生成密鑰
SecretKey k=kg.generateKey( );
(4) 經過對象序列化方式將密鑰保存在文件中
FileOutputStream f=new FileOutputStream("key1.dat");
ObjectOutputStream b=new ObjectOutputStream(f);
b.writeObject(k);
import java.io.*; import javax.crypto.*; public class Skey_DES{ public static void main(String args[]) throws Exception{ KeyGenerator kg=KeyGenerator.getInstance("DESede"); kg.init(168); SecretKey k=kg.generateKey( ); FileOutputStream f=new FileOutputStream("key1.dat"); ObjectOutputStream b=new ObjectOutputStream(f); b.writeObject(k); }
ClientSend
import java.io.*; import java.net.Socket; public class ClientSend { public static void main(String[] args) { Socket s = null; try { s = new Socket("192.168.56.1", 12345); }catch (IOException e) { System.out.println("未鏈接到服務器"); } try { DataInputStream input = new DataInputStream(s.getInputStream()); System.out.print("請輸入: \t"); String str = new BufferedReader(new InputStreamReader(System.in)).readLine(); MyBC turner = new MyBC(); String str1 = turner.turn(str); int length = 0, i = 0; while (str1.charAt(i) != '\0') { length++; i++; } String str2 = str1.substring(1, length - 1); SEnc senc = new SEnc(str2);//指定後綴表達式爲明文字符 senc.encrypt();//加密 }catch(Exception e) { System.out.println("客戶端異常:" + e.getMessage()); } File sendfile = new File("SEnc.dat"); File sendfile1 = new File("Keykb1.dat"); FileInputStream fis = null; FileInputStream fis1 = null; byte[] buffer = new byte[4096 * 5]; byte[] buffer1 = new byte[4096 * 5]; OutputStream os; if(!sendfile.exists() || !sendfile1.exists()){ System.out.println("客戶端:要發送的文件不存在"); return; } try { fis = new FileInputStream(sendfile); fis1 = new FileInputStream(sendfile1); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { PrintStream ps = new PrintStream(s.getOutputStream()); ps.println("111/#" + sendfile.getName() + "/#" + fis.available()); ps.flush(); } catch (IOException e) { System.out.println("服務器鏈接中斷"); } try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } try { os = s.getOutputStream(); int size = 0; while((size = fis.read(buffer)) != -1){ System.out.println("客戶端發送數據包,大小爲" + size); os.write(buffer, 0, size); os.flush(); } } catch (FileNotFoundException e) { System.out.println("客戶端讀取文件出錯"); } catch (IOException e) { System.out.println("客戶端輸出文件出錯"); }finally{ try { if(fis != null) fis.close(); } catch (IOException e) { System.out.println("客戶端文件關閉出錯"); } } try { PrintStream ps1 = new PrintStream(s.getOutputStream()); ps1.println("111/#" + sendfile1.getName() + "/#" + fis1.available()); ps1.flush(); } catch (IOException e) { System.out.println("服務器鏈接中斷"); } try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } try { os = s.getOutputStream(); int size = 0; while((size = fis1.read(buffer1)) != -1){ System.out.println("客戶端發送數據包,大小爲" + size); os.write(buffer1, 0, size); os.flush(); } } catch (FileNotFoundException e) { System.out.println("客戶端讀取文件出錯"); } catch (IOException e) { System.out.println("客戶端輸出文件出錯"); }finally{ try { if(fis1 != null) fis1.close(); } catch (IOException e) { System.out.println("客戶端文件關閉出錯"); } } try{ DataInputStream input = new DataInputStream(s.getInputStream()); String ret = input.readUTF(); System.out.println("服務器端返回過來的是: " + ret); } catch (Exception e) { e.printStackTrace(); }finally { if (s == null) { try { s.close(); } catch (IOException e) { System.out.println("客戶端 finally 異常:" + e.getMessage()); } } } } }
1人負責客戶端,一人負責服務器
使用密鑰協定來交換對稱密鑰。執行密鑰協定的標準算法是DH算法(Diffie-Hellman算法)
DH算法是創建在DH公鑰和私鑰的基礎上的, A須要和B共享密鑰時,A和B各自生成DH公鑰和私鑰,公鑰對外公佈而私鑰各自祕密保存。本實例將介紹Java中如何建立並部署DH公鑰和私鑰,以便後面一小節利用它建立共享密鑰。
編程思路:
(1) 讀取本身的DH私鑰和對方的DH公鑰
FileInputStream f1=new FileInputStream(args[0]); ObjectInputStream b1=new ObjectInputStream(f1); PublicKey pbk=(PublicKey)b1.readObject( ); FileInputStream f2=new FileInputStream(args[1]); ObjectInputStream b2=new ObjectInputStream(f2); PrivateKey prk=(PrivateKey)b2.readObject( );
(2) 建立密鑰協定對象
KeyAgreement ka=KeyAgreement.getInstance("DH");
(3) 初始化密鑰協定對象
ka.init(prk);
(4) 執行密鑰協定
ka.doPhase(pbk,true);
(5) 生成共享信息
byte[ ] sb=ka.generateSecret();
Key_DH:
import java.io.*; import java.math.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; public class Key_DH{ //三個靜態變量的定義從 // C:\j2sdk-1_4_0-doc\docs\guide\security\jce\JCERefGuide.html // 拷貝而來 // The 1024 bit Diffie-Hellman modulus values used by SKIP 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); } }
1人負責客戶端,一人負責服務器
使用Java計算指定字符串的消息摘要。
java.security包中的MessageDigest類提供了計算消息摘要的方法,
首先生成對象,執行其update()方法能夠將原始數據傳遞給該對象,而後執行其digest( )方法便可獲得消息摘要。具體步驟以下:
(1) 生成MessageDigest對象
MessageDigest m=MessageDigest.getInstance("MD5");
(2) 傳入須要計算的字符串
m.update(x.getBytes("UTF8" ));
(3) 計算消息摘要
byte s[ ]=m.digest( );
(4) 處理計算結果
Server修改:
String x= exp; MessageDigest m=MessageDigest.getInstance("MD5"); m.update(x.getBytes("UTF8")); byte s[ ]=m.digest( ); String res=""; for (int j=0; j<s.length; j++){ res +=Integer.toHexString((0x000000ff & s[j]) |0xffffff00).substring(6); } System.out.printf("md5Check:" + md5.equals(res));
Client修改:
String x= str2; MessageDigest m=MessageDigest.getInstance("MD5"); m.update(x.getBytes("UTF8")); byte s[ ]=m.digest( ); String result=""; for (int j=0; j<s.length; j++){ result+=Integer.toHexString((0x000000ff & s[j]) |0xffffff00).substring(6); }