当前位置: 首页 > 编程日记 > 正文

Java第四次实验

一、实验内容:

结对编程。运行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%

五、实验体会:

代码就是为了更好地使用计算机而服务。通过此课程的学习,我发觉了计算机的更多使用方法,

也明白了网络功能的实现与程序的关系。

转载于:https://www.cnblogs.com/hzy20/p/4572831.html

相关文章:

JS 面向对象编程之原型(prototype)

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 function Person(first, last) {this.first first;this.last last; } Person.prototype.fullName function() {return this.first this.last; } Person.prototype.fullNameReversed function() {…

idea自动捕获_Smilefie:如何通过检测微笑来自动捕获自拍

idea自动捕获by Rishav Agarwal通过里沙夫阿加瓦尔 Smilefie&#xff1a;如何通过检测微笑来自动捕获自拍 (Smilefie: how you can auto-capture selfies by detecting a smile) Ten second takeaway: use Python and OpenCV to create an app that automatically captures a …

hiho 1015 KMP算法 CF 625 B. War of the Corporations

#1015 : KMP算法 时间限制:1000ms单点时限:1000ms内存限制:256MB描述 小Hi和小Ho是一对好朋友&#xff0c;出生在信息化社会的他们对编程产生了莫大的兴趣&#xff0c;他们约定好互相帮助&#xff0c;在编程的学习道路上一同前进。 这一天&#xff0c;他们遇到了一只河蟹&#…

React 组件绑定点击事件,并且传参完整Demo

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.传数组下标给点击事件Demo&#xff1a; const A 65 // ASCII character codeclass Alphabet extends React.Component {constructor(props) {super(props);this.handleClick this.handleClick.bind…

ScaleYViewPager

https://github.com/eltld/ScaleYViewPager 转载于:https://www.cnblogs.com/eustoma/p/4572925.html

node mongoose_如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序

node mongooseby Arun Mathew Kurian通过阿伦马修库里安(Arun Mathew Kurian) 如何使用Express&#xff0c;Mongoose和Socket.io在Node.js中构建实时聊天应用程序 (How to build a real time chat application in Node.js using Express, Mongoose and Socket.io) In this tut…

结对项目开发电梯调度 - 整体设计

一、系统介绍 1&#xff0e; 功能描述 本电梯系统用来控制一台运行于一个具有16层的大楼电梯&#xff0c;它具有上升、下降、开门、关门、载客的基本功能。 大楼的每一层都有&#xff1a; (1) 两个指示灯: 这两个指示灯分别用于指示当前所在的层数和电梯的当前状态&#xff…

3.分支结构与循环结构

1 程序结构 程序结构分为顺序结构、分支结构、循环结构。分支结构有&#xff1a;if结构&#xff0c;if....else结构&#xff0c;if...else if....else &#xff0c;if...else结构&#xff0c;switch结构&#xff1b;循环结构有&#xff1a;while循环&#xff0c;do....while循环…

微信小程序 实现复制到剪贴版功能

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 实现API&#xff1a; wx.setClipboardData(Object object) API说明&#xff1a;设置系统剪贴板的内容 属性类型默认值是否必填说明支持版本datastring 是剪贴板的内容 successfunction 否接口调用成功…

数据结构面试题编程题_您下次编程面试时应该了解的顶级数据结构

数据结构面试题编程题by Fahim ul Haq通过Fahim ul Haq Niklaus Wirth, a Swiss computer scientist, wrote a book in 1976 titled Algorithms Data Structures Programs.瑞士计算机科学家Niklaus Wirth在1976年写了一本书&#xff0c;名为《 算法数据结构程序》。 40 yea…

oracle使用小技巧

批量禁用触发器 SELECT ALTER TRIGGER || trigger_name || DISABLE; FROM all_triggers; 这样就生成了一个禁用语句列表&#xff0c;复制到sql脚本执行界面&#xff0c;批量执行即可&#xff0c;类似的&#xff0c;可以用all_tables来批量删除表。 转载于:https://www.cnblogs…

if for switch语句

顺序语句&#xff1a;一行行执行条件语句:选择分支if语句 1、 if&#xff08;....&#xff09;//括号内是判断条件 { //程序代码&#xff0c;运算等等 } 2、 if&#xff08;....&#xff09;//括号内是判断条件 { //程序代码&#xff0c;运算等等 } else//如果不满足条件则执…

Apache Unable to find the wrapper https - did you forget to enable it when you configured PHP?

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 Apache Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? 问题解决办法&#xff1a; 打开配置文件 php.ini &#xff0c; 如图&#xff1a; …

文件魔术数字_如何使用魔术脚手架自动创建文件并节省时间

文件魔术数字Before we begin: This article uses JavaScript / Node.js example code, but you can port these concepts to any language using the right tools.开始之前&#xff1a;本文使用JavaScript / Node.js示例代码&#xff0c;但是您可以使用正确的工具将这些概念移…

Sql Server统计报表案例

场景&#xff1a;查询人员指定年月工作量信息 USE [Test] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER procedure [dbo].[GetWorkLoadMain] year int, month int, UserId varchar(50) as begindeclare day varchar(50)set dayCAST(year as varchar)-RIGHT((00…

运行报表时提示输入用户名和密码

在AX2012运行报表是总是提示用户输入用户名和密码&#xff1a; 尝试输入登陆名和密码&#xff0c;点击查看报表&#xff0c;出现如下错误&#xff1a; 因为AX2012的报表使用的针对AX2012客制化的SSRS&#xff0c;而要求输入登录名和密码是SSRS报表的数据源设置导致的。在SSRS管…

CSS 文字,边框实现从左至右颜色渐变

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 1.文本从左至右颜色渐变 效果图&#xff1a; 2.边框从左至右颜色渐变 效果图&#xff1a; 实现代码&#xff1a; 1.文本从左至右颜色渐变实现代码&#xff1a; <!DOCTYPE html> <html>&l…

如何使用Create-React-App和自定义服务人员构建PWA

Note: This is not a primer on create-react-app or what a service worker is. This post assumes prior knowledge of both.注意&#xff1a;这不是create-react-app或服务工作者的入门。 这篇文章假定两者都有先验知识。 So, I recently had the opportunity to work on a…

inline-block空隙怎么解决

方法一&#xff1a;移除空格 元素间留白间距出现的原因就是标签段之间的空格&#xff0c;因此&#xff0c;去掉HTML中的空格&#xff0c;自然间距就木有了。考虑到代码可读性&#xff0c;显然连成一行的写法是不可取的&#xff0c;我们可以&#xff1a; <div class"spa…

php 网络请求 get请求和post请求

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 代码记录 <?php header(content-type:application:json;charsetutf8); header(Access-Control-Allow-Origin:*); //header(Access-Control-Allow-Methods:POST); header(Access-Control-Allow-He…

docker查看现有容器_如何使用Docker将现有应用程序推送到容器中

docker查看现有容器by Daniel Newton丹尼尔牛顿 如何使用Docker将现有应用程序推送到容器中 (How to shove an existing application into containers with Docker) I have finally got round to learning how to use Docker past the level of knowing what it is and does w…

巧妙使用Firebug插件,快速监控网站打开缓慢的原因

巧妙使用Firebug插件&#xff0c;快速监控网站打开缓慢的原因 原文 巧妙使用Firebug插件&#xff0c;快速监控网站打开缓慢的原因 很多用户会问&#xff0c;我的网站首页才50KB&#xff0c;打开网页用了近60秒才打开&#xff1f;如何解释&#xff1f; 用户抱怨服务器运行缓…

第二阶段第三次站立会议

昨天做了什么&#xff1a;写了部分购物车的功能 今天要干什么&#xff1a;修改后台代码的错误 遇到的困难&#xff1a;没有困难转载于:https://www.cnblogs.com/jingxiaopu/p/7109774.html

微信小程序生成小程序二维码 php 直接可以用

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 小程序需要先上线才能生成二维码 HTTP请求的效果图&#xff1a; 小程序展示的效果图&#xff1a; 小程序展示二维码源码&#xff1a; 请求二维码图片base64路径&#xff0c;点击预览图片 onLoad: func…

vue和react相同点_我在React和Vue中创建了相同的应用程序。 这是区别。

vue和react相同点by Sunil Sandhu由Sunil Sandhu 我在React和Vue中创建了相同的应用程序。 这是区别。 (I created the same app in React and Vue. Here are the differences.) Having used Vue at my current workplace, I had a fairly solid understanding of how it all …

Filter(过滤器)

一、Filter过滤器(重要)     Javaweb中的过滤器可以拦截所有访问web资源的请求或响应操作。 1、Filter快速入门     1.1、步骤:      1. 创建一个类实现Filter接口      2. 重写接口中方法 doFilter方法是真正过滤的。      3. 在web.xml文件中配置 …

css3实现3D立体翻转效果

1、在IE下无法显示翻转效果&#xff0c;火狐和谷歌可以 1 /*样式css*/2 3 .nav-menu li {4 display: inline;5 }6 .nav-menu li a {7 color: #fff;8 display: block;9 text-decoration: none;10 overflow: visible;11 line-height: 40px;12 font-…

Ant Design 入门-参照官方文档使用组件

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 先来一个按钮组件使用的对比,官方文档的(不能直接用)和实际能用的。 官网demo: import { Table, Divider, Tag } from antd;const columns = [{title: Name,dataIndex: name,key: name,render: text =…

如何用JavaScript的回调函数做出承诺

by Adham El Banhawy由Adham El Banhawy 如何用JavaScript的回调函数做出承诺 (How to make a Promise out of a Callback function in JavaScript) Back-end developers run into challenges all the time while building applications or testing code. As a developer who …

VMware里的linux系统里的命令行里会有bee的声音,要如何关掉

VMware里的linux系统里的命令行里会有bee的声音&#xff0c;要如何关掉 取消bell报警声的方法&#xff1a;登陆linux系统vi /etc/inputrc找到set bell-style none 将前面的&#xff03;去掉&#xff0c;之后重启系统即可解决声音问题若不见效可以通过下面的方式解决下bell-styl…