Use Mina when a server makes a plain text message or multimedia message encryption session

Source: Internet
Author: User

First of all, for the basic use of Mina here is not much to say, has been reproduced before a very detailed description. This time to share is to use the Mina framework to customize the codec, to send plain text and non-plain text messages, with PBE encryption.

First define the packet to be sent, before always want to use Mina for picture speech, short video transmission, the multimedia information encapsulated into a class, plain text file encapsulated into a class. The multiplexing decoder is then used, although this method works, but both send and receive skip the handler layer directly. It is inconvenient to deal with business logic at the end.

Then try the value using one of the format information classes, the message type is only plain text or non-plain text identification. A string type that sends JSON data when it is sent in real time. Then a byte array. When it is plain text information is, the identity is ' + ', the byte array is null, this does not cause the new information class to allocate extra memory. In the case of non-plain text information, the identity is '-'. The byte array holds the multimedia information.

The next important step is to write the encoder and decoder, the idea is very simple, according to the information sent by the corresponding encoding, according to the identity of the corresponding decoding. Then there is the encryption, where PBE symmetric encryption is used. The encryption time is encoded when the encoder is encoded. Decryption is when the decoder is decoded. Encryption speed I tested it a bit. 4.1M encryption: 191ms decryption: 198ms 15M encryption: 600ms decryption: 570ms, should also be able to.

The following code is attached:

1. Information class

/**
* symbol = ' + ': pure text file
* symbol = '-': Non-pure document
* @author Administrator
*/
public class Imomomsg {
Public char symbol;//to determine if it is a plain text file
Public String msgjson;//contains an explanation of the picture details
Public byte[] msgbytes;//pictures
}

2. Encoding Class

Package com.imomo_codecfactory;

Import Java.nio.charset.Charset;
Import Java.nio.charset.CharsetEncoder;

Import org.apache.commons.codec.binary.Base64;
Import Org.apache.mina.core.buffer.IoBuffer;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.ProtocolEncoderAdapter;
Import Org.apache.mina.filter.codec.ProtocolEncoderOutput;

Import COM.IMOMO_MSG.IMOMOMSG;
Import Com.security.PBE;

public class Imomoencoder extends Protocolencoderadapter {
Charsetencoder encoder = charset.forname ("Utf-8"). Newencoder ();
Plain text send format: header tag (char) + information Length (int) + text message (encryption byte[])
Non-plain text send format: header tag (char) + text message length (int) + text message (encryption byte[]) + Multimedia information Length (int) + Multimedia information (encryption byte[])
@Override
public void Encode (iosession session, Object msg, protocolencoderoutput out)
Throws Exception {
Imomomsg momsg = (imomomsg) msg;
char symbol = Momsg.symbol;
try {
if (symbol = = ' + ') {
byte[] Msgjsonbyte = Pbe.encrypt (MoMsg.msgJson.getBytes ());//encryption
System.out.println ("--Send text message =" + Momsg.msgjson);
int msglen = Msgjsonbyte.length;
2: The beginning of the head symbol, here is '-+, 4 indicates the length of the bit
Iobuffer io = iobuffer.allocate (2 + 4 + msglen). Setautoexpand (
true);
Io.putchar (symbol);
Io.putint (Msglen);
Io.put (Msgjsonbyte);
Io.flip ();
Out.write (IO);
} else if (symbol = = '-') {
byte[] Msgjsonbyte = Pbe.encrypt (MoMsg.msgJson.getBytes ());//encryption
byte[] msgbytes = Pbe.encrypt (momsg.msgbytes);
System.out.println ("--send Multimedia message =" + Momsg.msgjson
+ "Msgbyteslen =" + msgbytes.length);
int Textlen = msgjsonbyte.length;//literal information length
int msgbyteslen = msgbytes.length;//picture length
Iobuffer io = iobuffer.allocate (
2 + 4 + 4 + Textlen + msgbyteslen). Setautoexpand (True);
Io.putchar (symbol);
Io.putint (Textlen);
Io.put (Msgjsonbyte);
Io.putint (Msgbyteslen);
Io.put (msgbytes);
Io.flip ();
Out.write (IO);
}
} catch (Exception e) {
E.printstacktrace ();
}
}

}

3. Decoding class

Package com.imomo_codecfactory;

Import Java.io.FileOutputStream;
Import Java.nio.channels.FileChannel;
Import Java.nio.charset.Charset;
Import Java.nio.charset.CharsetDecoder;
Import Java.util.Date;

Import Org.apache.mina.core.buffer.IoBuffer;
Import org.apache.mina.core.session.IoSession;
Import Org.apache.mina.filter.codec.CumulativeProtocolDecoder;
Import Org.apache.mina.filter.codec.ProtocolDecoderOutput;
Import Org.apache.mina.filter.codec.demux.MessageDecoder;
Import Org.apache.mina.filter.codec.demux.MessageDecoderResult;

Import COM.IMOMO_MSG.IMOMOMSG;
Import Com.security.PBE;

public class Imomodecoder extends Cumulativeprotocoldecoder {
Charsetdecoder decoder = charset.forname ("Utf-8"). Newdecoder ();

@Override
Protected Boolean Dodecode (iosession session, Iobuffer in,
Protocoldecoderoutput out) throws Exception {
Imomomsg momsg = new Imomomsg ();
int pos = In.position ();
int remaining = in.remaining ();
try {
Judging length, opening symbol is char type
if (remaining < 2) {
In.position (POS);
return false;
}
char symbol = In.getchar ();//equivalent to consumption of byte-out stream
Momsg.symbol = symbol;
if (symbol = = ' + ') {
int Msgjsonlen = 0;//Msgjson length
Determine if it is enough to parse out the length
Msgjsonlen = In.getint ();
if (Remaining-2 < Msgjsonlen | | Msgjsonlen < 0) {
In.position (POS);
return false;
}
byte[] temp = new Byte[msgjsonlen];
In.get (temp);//Gets encrypted after a byte array
Momsg.msgjson = new String (pbe.deciphering (temp));
Out.write (MOMSG);
} else if (symbol = = '-') {
Receive text messages
int Msgjsonlen = 0;//Msgjson length
int Msgbyteslen = 0;//msgbytes length
Msgjsonlen = In.getint ();
if (Remaining-2 < Msgjsonlen | | Msgjsonlen < 0) {
In.position (POS);
return false;
}
byte[] Temp1 = new Byte[msgjsonlen];
In.get (TEMP1);//Gets encrypted after a byte array
Momsg.msgjson = new String (pbe.deciphering (TEMP1));
Receive picture information
Msgbyteslen = In.getint ();
if (Remaining-2-4-4-Msgjsonlen < Msgbyteslen
|| Msgbyteslen < 0) {
In.position (POS);
return false;
}
byte[] Temp2 = new Byte[msgbyteslen];
In.get (TEMP2);//Gets encrypted after a byte array
Momsg.msgbytes = pbe.deciphering (TEMP2);
Out.write (MOMSG);
}
} catch (Exception e) {
E.printstacktrace ();
In.position (POS);
return false;
}
return true;
}
}

If the codec is not ripe, you can refer to the Mina development manual.

Test to send a 15m video:

In the client handler class:

@Override
public void sessionopened (Iosession session) throws Exception {
Imomomsg momomsg = new Imomomsg ();
Jsonobject Textjson = new Jsonobject ();
Textjson.put ("type", "Login");
Textjson.put ("id", "201513");
Textjson.put ("pwd", "1234");
Momomsg.msgjson = Textjson.tojsonstring ();
Momomsg.symbol = ' + ';
Session.write (MOMOMSG);

Send picture information
Jsonobject Multijson = new Jsonobject ();
Multijson.put ("type", "pic");
Multijson.put ("Sender", "001");
Multijson.put ("Getter", "002");
FileInputStream FileInputStream = new FileInputStream ("F:\\moshou.avi");
FileChannel channel = Fileinputstream.getchannel ();
Bytebuffer Bytebuffer = bytebuffer.allocate ((int) channel.size ());
Bytebuffer.clear ();
Channel.read (Bytebuffer);
Imomomsg MOMOMSG2 = new Imomomsg ();
Momomsg2.msgjson = Multijson.tojsonstring ();
Momomsg2.msgbytes = Bytebuffer.array ();
Momomsg2.symbol = '-';
Session.write (MOMOMSG2);
Fileinputstream.close ();
Channel.close ();

}

In Server handler:

public void Messagereceived (iosession session, Object message)
Throws Exception {
Super.messagereceived (session, message);
Imomomsg momomsg = (imomomsg) message;
if (Momomsg.symbol = = ' + ') {
String Msgjson = Momomsg.msgjson;
SYSTEM.OUT.PRINTLN ("Server receives plain Text message:" + Msgjson);
} else if (Momomsg.symbol = = '-') {
String Msgjson = Momomsg.msgjson;
SYSTEM.OUT.PRINTLN ("The server received the multimedia information:" + Msgjson + "Multimedia information Length" + moMoMsg.msgBytes.length);
FileOutputStream fileout = new FileOutputStream ("f:\\"
+ New Date (). getminutes () + "-.avi");
FileChannel FC = Fileout.getchannel ();
Fileout.write (momomsg.msgbytes);
Fc.close ();
Fileout.close ();
}

}

Console printing:

Client:

This time of encryption: 774
This time of encryption: 651
--Send Multimedia message = {"Getter": "002", "Sender": "001", "type": "Pic"} Msgbyteslen = 16174624

Server:

This decryption time: 177

This decryption time: 597
The server receives the multimedia information: {"getter": "002", "Sender": "001", "type": "Pic"} Multimedia information length 16174616

From the above can be seen: encryption whether the text information encryption or multimedia file encryption, are more time-consuming, the decryption is relatively fast.

Concrete Project: http://download.csdn.net/detail/u011102153/8615791

Use Mina when a server makes a plain text message or multimedia message encryption session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.