Netty傻瓜教程(七):聊天加密

Channel是通道,那麼pipeline就是通道里面的管道,具體的解釋能夠參考:http://ifeve.com/channel-pipeline/,咱們在管道里加入消息的編碼和解碼器:java

bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast("HBeat", new IdleStateHandler(
						ConstantManager.HEART_BEAT + 10,
						ConstantManager.HEART_BEAT, 0));// 心跳
				pipeline.addLast("MsgDecoder", new ProtobufDecoder());// 解碼器
				pipeline.addLast("MsgEncoder", new ProtobufEncoder());// 編碼器
				pipeline.addLast("handler", new AppServerHandler());// 消息處理器

			}
		});

1. ProtobufEncoder()方法對消息進行編碼,具體實現以下:bootstrap

public class ProtobufEncoder extends MessageToByteEncoder<Message> {
	/**
	 * 日誌對象
	 */
	private final Logger Log = LoggerFactory.getLogger(getClass());

	@Override
	protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out)
			throws Exception {

		byte[] bytes = msg.toByteArray();// 將對象轉換爲byte

		// 加密消息體
		ThreeDES des = ctx.channel().attr(AppAttrKeys.ENCRYPT).get();
		byte[] encryptByte = des.encrypt(bytes);
		int length = encryptByte.length;// 讀取消息的長度

		ByteBuf buf = Unpooled.buffer(2 + length);
		buf.writeShort(length);// 先將消息長度寫入,也就是消息頭
		buf.writeBytes(encryptByte);// 消息體中包含咱們要發送的數據
		out.writeBytes(buf);

		Log.info("[APP-SERVER][SEND][remoteAddress:"
				+ ctx.channel().remoteAddress() + "][total length:" + length
				+ "][bare length:" + msg.getSerializedSize() + "]:\r\n"
				+ msg.toString());

	}

}

1. 必需要寫覆蓋父類的方法encode,在其中對消息進行DES加密,des.encrypt(bytes)ide

下面是加密方法:編碼

public byte[] encrypt(byte[] plainByte) {

		byte[] cipherByte = null;
		try {
			DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory
					.getInstance("DESede");
			SecretKey securekey = keyFactory.generateSecret(dks);

			Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, securekey);
			cipherByte = cipher.doFinal(plainByte);
		} catch (Exception e) {
			Log.error(e.getMessage(), e);
		}
		return cipherByte;
	}
相關文章
相關標籤/搜索