Socket通信Des加密笔记.docx
《Socket通信Des加密笔记.docx》由会员分享,可在线阅读,更多相关《Socket通信Des加密笔记.docx(53页珍藏版)》请在冰豆网上搜索。
Socket通信Des加密笔记
Socket通信及Des之CBC加密解密
目录
1.1Socket通信:
2
1.1.1socket基本概念2
1.1.2建立socket连接步骤3
1.1.3通信实例3
1.1.4使用Socket应注意问题:
13
1.2Des之CBC加密解密13
1.2.1DES简单介绍13
1.2.2CBC加密实现的机理13
1.2.3使用CBC和Base64加密解密关键代码:
14
1.2.4使用DSE加密解密注意问题:
24
1.3Socket通信及Des之CBC加密解密完整源码:
24
1.3.1Java服务代码:
24
1.3.2Android客户端代码:
31
1.1Socket通信:
1.1.1socket基本概念
套接字(socket)是通信的基石,是支持TCP/IP协议的网络通信的基本操作单元。
它是网络通信过程中端点的抽象表示,包含进行网络通信必须的五种信息:
连接使用的协议,本地主机的IP地址,本地进程的协议端口,远地主机的IP地址,远地进程的协议端口
1.1.2建立socket连接步骤
I.简单介绍:
建立Socket连接至少需要一对套接字,其中一个运行于客户端,称为ClientSocket,另一个运行于服务器端,称为ServerSocket。
套接字之间的连接过程分为三个步骤:
服务器监听,客户端请求,连接确认。
II.服务器监听
服务器端套接字并不定位具体的客户端套接字,而是处于等待连接的状态,实时监控网络状态,等待客户端的连接请求。
III.客户端请求
指客户端的套接字提出连接请求,要连接的目标是服务器端的套接字。
为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器端套接字的地址和端口号,然后就向服务器端套接字提出连接请求。
IV.连接确认
当服务器端套接字监听到或者说接收到客户端套接字的连接请求时,就响应客户端套接字的请求,建立一个新的线程,把服务器端套接字的描述发给客户端,一旦客户端确认了此描述,双方就正式建立连接。
而服务器端套接字继续处于监听状态,继续接收其他客户端套接字的连接请求。
1.1.3通信实例
I.Java服务端代码:
importjava.io.IOException;
import.InetSocketAddress;
import.UnknownHostException;
importjava.nio.ByteBuffer;
importjava.nio.CharBuffer;
importjava.nio.channels.SelectionKey;
importjava.nio.channels.Selector;
importjava.nio.channels.ServerSocketChannel;
importjava.nio.channels.SocketChannel;
importjava.nio.charset.Charset;
importjava.nio.charset.CharsetDecoder;
importjava.util.Collection;
importjava.util.Hashtable;
importjava.util.Iterator;
importjava.util.Set;
publicclassMsgServer{
publicSelectorsel=null;
publicServerSocketChannelserver=null;
publicSocketChannelsocket=null;
publicintthisport=4900;
privateStringresult=null;
privateHashtableuserlists;
privateSocketChannelreadingsocket=null;
publicMsgServer(){
System.out.println("Insidestartserver");
}
publicMsgServer(intport){
System.out.println("Insidestartserver");
thisport=port;
}
publicvoidinit()throwsIOException,UnknownHostException{
System.out.println("Insideinitialization");
sel=Selector.open();
server=ServerSocketChannel.open();
server.configureBlocking(false);
InetSocketAddressisa=newInetSocketAddress("192.85.1.235",
thisport);
server.socket().bind(isa);
userlists=newHashtable();
}
publicvoidstartServer()throwsIOException
{
init();
server.register(sel,SelectionKey.OP_ACCEPT);
while(sel.select()>0)
{
Set
>readyKeys=sel.selectedKeys();
Iterator
>it=readyKeys.iterator();
while(it.hasNext())
{
SelectionKeysk=(SelectionKey)it.next();
it.remove();
if(sk.isAcceptable())
{
ServerSocketChannelssc=(ServerSocketChannel)sk.channel();
socket=(SocketChannel)ssc.accept();
System.out.println(socket.toString());
/*设置为非阻塞模式*/
socket.configureBlocking(false);
Stringsocketname=socket.socket().getRemoteSocketAddress().toString();
socket.register(sel,SelectionKey.OP_READ);
sk.interestOps(SelectionKey.OP_ACCEPT);
userlists.put(socketname,socket);
System.out.println(socketname+"已经连接了!
!
");
}
if(sk.isReadable())
{
System.out.println("startwrite...");
readingsocket=(SocketChannel)sk.channel();
Stringret=readMessage(readingsocket);
if(ret.equalsIgnoreCase("@@@@@hasleft!
"))
{
sk.cancel();
readingsocket.close();
userlists.remove(readingsocket.socket().getRemoteSocketAddress().toString());
System.out.println("leftmessage:
"+ret.replace("@@@@@",readingsocket.socket().getRemoteSocketAddress().toString()));
sendMessage(ret.replace("@@@@@",readingsocket.socket().getRemoteSocketAddress().toString()));
}
elseif(ret.length()>0)
{
//sk.cancel();
System.out.println("sendservermsg:
"+ret);
//传回信息
sendMessage(ret);
}
}
}
}
}
publicvoidsendMessage(Stringmsg)throwsIOException{
ByteBufferbuffer=ByteBuffer.allocate(1024);
buffer=ByteBuffer.wrap(msg.getBytes());
//ByteBufferbuffer=ByteBuffer.wrap(msg.getBytes("UTF-8"));
Collectionchannels=userlists.values();
SocketChannelsc;
for(Objecto:
channels){
sc=(SocketChannel)o;
sc.write(buffer);
buffer.flip();
try{
Thread.sleep(500);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
publicStringreadMessage(SocketChannelsc){
ByteBufferbuf=ByteBuffer.allocate(1024);
try{
sc.read(buf);
buf.flip();
Charsetcharset=Charset.forName("utf-8");
CharsetDecoderdecoder=charset.newDecoder();
CharBuffercharBuffer=decoder.decode(buf);
result=charBuffer.toString();
System.out.println(result);
}catch(IOExceptione){
result="@@@@@hasleft!
";
}
returnresult;
}
publicstaticvoidmain(Stringargs[]){
MsgServerms=newMsgServer();
try{
ms.startServer();
}catch(IOExceptione){
e.printStackTrace();
System.exit(-1);
}
}
}
II.Android客户端代码:
(1)客户端(android)Activity:
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassMsgClientextendsActivity
{
/**阻塞Socket客户端*/
privateEditTextedt;
publicvoidonCreate(BundlesavedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)this.findViewById(R.id.edt);
Buttonbut=(Button)this.findViewById(R.id.Button);
but.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv)
{
//TODOAuto-generatedmethodstub
Intentintent=newIntent(MsgClient.this,ReceiveMessage.class);
Stringmsg=edt.getText().toString();
intent.putExtra("msg",msg);
//启动服务
MsgClient.this.startService(intent);
}
});
}
}
(2)客户端(android)Socket连接类:
importjava.io.IOException;
import.InetSocketAddress;
importjava.nio.ByteBuffer;
importjava.nio.CharBuffer;
importjava.nio.channels.SocketChannel;
importjava.nio.charset.CharacterCodingException;
importjava.nio.charset.Charset;
importjava.nio.charset.CharsetDecoder;
importandroid.app.Notification;
importandroid.app.NotificationManager;
importandroid.app.PendingIntent;
importandroid.app.Service;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.os.Binder;
importandroid.os.IBinder;
importandroid.widget.Toast;
publicclassReceiveMessageextendsService{
privateSocketChannelclient=null;
privateInetSocketAddressisa=null;
privateintNOTIFICATION=R.string.local_service_connected;
//privateStringmsg="";
publicvoidonCreate()
{
super.onCreate();
ConnectToServer();
StartServerListener();
}
publicvoidonDestroy()
{
super.onDestroy();
DisConnectToServer();
}
publicvoidonStart(Intentintent,intstartId)
{
super.onStart(intent,startId);
Stringmsg=intent.getStringExtra("msg");
if(msg.length()>0)
{
SendMessageToServer(msg);
}
System.out.println("messageiscomming:
"+msg);
}
privatevoidStartServerListener(){
//TODOAuto-generatedmethodstub
ServerListenera=newServerListener();
a.start();
}
//链接服务端
publicvoidConnectToServer()
{
try{
client=SocketChannel.open();
isa=newInetSocketAddress("192.85.1.235",4900);
client.connect(isa);
//client.configureBlocking(false);
}
catch(IOExceptione)
{
e.printStackTrace();
}
}
//断开服务端
privatevoidDisConnectToServer(){
//TODOAuto-generatedmethodstub
try
{
client.close();
}
catch(IOExceptione){e.printStackTrace();}
}
publicIBinderonBind(Intentintent){
//Stringmsg=intent.getStringExtra("msg");
//System.out.println("绑定的数据"+msg);
returnmBinder;
}
publicclassLocalBinderextendsBinder
{
ReceiveMessagegetService()
{
returnReceiveMessage.this;
}
}
privatefinalIBindermBinder=newLocalBinder();
privatevoidSendMessageToServer(Stringmsg2)
{
//TODOAuto-generatedmethodstub
try
{
ByteBufferbytebuf=ByteBuffer.allocate(1024);
bytebuf=ByteBuffer.wrap(msg2.getBytes("UTF-8"));
client.write(bytebuf);
bytebuf.flip();
}
catch(IOExceptione)
{
e.printStackTrace();
}
}
publicvoidshownotification(Stringtab)
{
NotificationManagerbarmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notificationmsg2=newNotification(android.R.drawable.stat_notify_chat,"信息",System.currentTimeMillis());
PendingIntentcontentIntent=PendingIntent.getActivity(this,0,newIntent(this,MsgClient.class),PendingIntent.FLAG_ONE_SHOT);
System.out.println("服务器端发回信息了信息:
"+contentIntent);
msg2.setLatestEventInfo(this,"服务器端发回信息了","信息:
"+tab,contentIntent);
barmanager.notify(NOTIFICATION,msg2);
//Toast.makeText(ReceiveMessage.this,tab,Toast.LENGTH_SHORT).show();
//System.out.println(tab);
}
publicclassServerListenerextendsThread
{
publicvoidrun()
{
try
{
while(true)
{
ByteBufferbuf=ByteBuffer.allocate(1024);
client.read(buf);
buf.flip();
Charsetcharset=Charset.forName("utf-8");
CharsetDecoderdecoder=charset.newDecoder();
CharBuffercharbuffer;
charbuffer=decoder.decode(buf);
Stringresult=charbuffer.toString();
if(result.length()>0)
{
//System.out.println("result"+"%%%%%%%%%5555"+result);
shownotification(result);
}
}
}
catch(CharacterCodingExceptione)
{
e.printStackTrace();
}
catch(IOExceptione)
{
e.printStackTrace();
}
}
}
}
1.1.4使用Socket应注意问题:
(1)服务端必须先与客户端运行,才能通信
(2)客户端和服务端所使用的编码方式要相同,否则会出现乱码问题。
1.2Des之CBC加密解密
1.2.1DES简单介绍
I.DES是一种第一次解密算法
对称加密算法就是能将数据加解密。
加密的时候用密钥对数据进行加密,解密的时候使用同样的密钥对数据进行解密。
II.交互模型
(1)消息传递双方约定密钥,通常由消息发送方(甲方)构建密钥通