20145325张梓靖 实验五 "JAVA的网络编程"
实验内容
使用 JVAV语言 进行网络编程
对明文进行加密
设计过程
我完成的是客户端,服务端同伴 20145308刘昊阳 地址为:http://www.cnblogs.com/yg961022/p/5471201.html
先生成 DES 秘钥
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair kp=kpg.genKeyPair();
PublicKey pbkey=kp.getPublic();
PrivateKey prkey=kp.getPrivate();
FileOutputStream f1=new FileOutputStream("Skey_RSA_pub.dat");
ObjectOutputStream b1=new ObjectOutputStream(f1);
b1.writeObject(pbkey);
FileOutputStream f2=new FileOutputStream("Skey_RSA_priv.dat");
ObjectOutputStream b2=new ObjectOutputStream(f2);
b2.writeObject(prkey);
FileInputStream f=new FileInputStream("key1.dat");
ObjectInputStream b=new ObjectInputStream(f);
Key k=(Key)b.readObject( );
byte[ ] kb=k.getEncoded( );
FileOutputStream f2=new FileOutputStream("keykb1.dat");
f2.write(kb);
for(int i=0;i<kb.length;i++){
System.out.print(kb[i]+",");
}
- 将输入的明文"Hello World! 20145325"进行加密
String s="Hello World! 20145325";
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[]=s.getBytes("UTF8");
for(int i=0;i<ptext.length;i++){
System.out.print(ptext[i]+",");
}
System.out.println("");
byte ctext[]=cp.doFinal(ptext);
for(int i=0;i<ctext.length;i++){
System.out.print(ctext[i] +",");
}
FileOutputStream f2=new FileOutputStream("SEnc.dat");
f2.write(ctext);
- 将 DES 的秘钥用服务端的公钥进行 RSA 加密:
FileInputStream f = new FileInputStream("Skey_RSA_pub.dat");
ObjectInputStream b = new ObjectInputStream(f);
RSAPublicKey pbk = (RSAPublicKey) b.readObject();
BigInteger e = pbk.getPublicExponent();
BigInteger n = pbk.getModulus();
System.out.println("e= " + e);
System.out.println("n= " + n);
byte ptext[] = s.getBytes("UTF8");
BigInteger m = new BigInteger(ptext);
BigInteger c = m.modPow(e, n);
System.out.println("c= " + c);
String cs = c.toString();
BufferedWriter out =
new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Enc_RSA.dat")));
out.write(cs, 0, cs.length());
out.close();
- 将密文和加密的秘钥通过网络编程传输过去:
Socket socket = null;
InputStream is = null;
OutputStream os = null;
//服务器端IP地址
String serverIP = "192.168.199.107";
//服务器端端口号
int port = 10000;
//发送内容
String data[] ={"**","**"};
try {
//建立连接
socket = new Socket(serverIP,port);
//初始化流
os = socket.getOutputStream();
is = socket.getInputStream();
byte[] b = new byte[1024];
for(int i = 0;i < data.length;i++){
//发送数据
os.write(data[i].getBytes());
//接收数据
int n = is.read(b);
//输出反馈数据
System.out.println("服务器反馈:" + new String(b,0,n));
}
} catch (Exception e) {
e.printStackTrace(); //打印异常信息
}finally{
try {
//关闭流和连接
is.close();
os.close();
socket.close();
} catch (Exception e2) {}
}
- 服务端打开监听,客户端进行传输,服务端收到数据,然后再进行解密