標籤:
一、實驗內容:
結對程式設計。運行TCP代碼,結對進行,一人伺服器,一人用戶端;利用加解密程式碼封裝,編譯運行代碼,一人加密,一人解密;
整合代碼,密後通過TCP發送。
二、代碼:
伺服器:
// file name:ComputeTCPServer.java
import java.net.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
public class ComputeTCPServer{
public static void main(String srgs[]) throws Exception {
ServerSocket sc = null;
Socket socket=null;
try {
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 aline2=in.readLine();
BigInteger c=new BigInteger(aline2);
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();
//System.out.println("d= "+d);
//System.out.println("n= "+n);
BigInteger m=c.modPow(d,n);
//System.out.println("m= "+m);
byte[] keykb=m.toByteArray();
//String aline3=new String(mt,"UTF8");
//String aline3=parseByte2HexStr(byte buf[]);
String aline=in.readLine();//讀取用戶端傳送來的資料
//FileInputStream f2=new FileInputStream("keykb1.dat");
//int num2=f2.available();
//byte[] keykb=new byte[num2];
//f2.read(keykb);
byte[] ctext=parseHexStr2Byte(aline);
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); //通過網路輸出資料流返回結果給用戶端
/*String aline2=in.readLine();
BigInteger c=new BigInteger(aline2);
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();
//System.out.println("d= "+d);
//System.out.println("n= "+n);
BigInteger m=c.modPow(d,n);
//System.out.println("m= "+m);
byte[] mt=m.toByteArray();
//String aline3=new String(mt,"UTF8");*/
String aline3=in.readLine();
String x=p;
MessageDigest m2=MessageDigest.getInstance("MD5");
m2.update(x.getBytes( ));
byte a[ ]=m2.digest( );
String result="";
for (int i=0; i<a.length; i++){
result+=Integer.toHexString((0x000000ff & a[i]) |
0xffffff00).substring(6);
}
System.out.println(result);
if(aline3.equals(result)){
System.out.println("匹配成功");
}
out.println("匹配成功");
out.close();
in.close();
sc.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0‘ + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1 ), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
用戶端:
// file name:ComputeTCPClient.java
import java.net.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
public class ComputeTCPClient {
public static void main(String srgs[]) throws Exception{
try {
KeyGenerator kg=KeyGenerator.getInstance("DESede");//方法getInstance( )的參數為字串類型,指定密碼編譯演算法的名稱
kg.init(168); //該步驟一般指定密鑰的長度
SecretKey k=kg.generateKey( );//產生密鑰
byte[] ptext2=k.getEncoded();
//String kstr=parseByte2HexStr(kb);
//建立串連特定伺服器的指定連接埠的Socket對象
//Socket socket = new Socket("192.168.155.4", 4421);
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));
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();
//System.out.println("e= "+e);
//System.out.println("n= "+n);
//byte ptext2[]=kstr.getBytes("UTF8");
BigInteger m=new BigInteger(ptext2);
BigInteger c=m.modPow(e,n);
//System.out.println("c= "+c);
String cs=c.toString( );
out.println(cs); //通過網路傳送到伺服器
System.out.print("請輸入待發送的資料:");
String s=stdin.readLine(); //從鍵盤讀入待發送的資料
Cipher cp=Cipher.getInstance("DESede");
cp.init(Cipher.ENCRYPT_MODE, k);
byte ptext[]=s.getBytes("UTF8");
byte ctext[]=cp.doFinal(ptext);
String str=parseByte2HexStr(ctext);
out.println(str); //通過網路傳送到伺服器
String x=s;
MessageDigest m2=MessageDigest.getInstance("MD5");
m2.update(x.getBytes( ));
byte a[ ]=m2.digest( );
String result="";
for (int i=0; i<a.length; i++){
result+=Integer.toHexString((0x000000ff & a[i]) |
0xffffff00).substring(6);
}
System.out.println(result);
out.println(result);
/*s=result;
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();
//System.out.println("e= "+e);
//System.out.println("n= "+n);
byte ptext2[]=s.getBytes("UTF8");
BigInteger m=new BigInteger(ptext2);
BigInteger c=m.modPow(e,n);
//System.out.println("c= "+c);
String cs=c.toString( );
out.println(cs); //通過網路傳送到伺服器*/
str=in.readLine();//從網路輸入資料流讀取結果
System.out.println( "從伺服器接收到的結果為:"+str); //輸出伺服器返回的結果
}
catch (Exception e) {
System.out.println(e);
}
finally{
//stdin.close();
//in.close();
//out.close();
//socket.close();
}
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0‘ + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
三、實驗:(最終結果)
四、實驗中遇到的問題:
1.關於IP地址:
可以通過命令列查看IP地址
2.用戶端和伺服器串連時對socket的host理解不夠,之前出現串連失敗的地方,後來放棄了書上getbyname的方法,
自己設定了127.0.0.1本機地址,也可以實現兩機間通訊。
步驟 |
耗時(min) |
百分比 |
需求分析 |
20 |
15% |
設計 |
20 |
15% |
代碼實現 |
60 |
46% |
測試 |
20 |
15% |
分析總結 |
10 |
8% |
五、實驗體會:
代碼就是為了更好地使用電腦而服務。通過此課程的學習,我發覺了電腦的更多使用方法,
也明白了網路功能的實現與程式的關係。
Java第四次實驗