| 1 | package net.minecraft.network;
|
| 2 |
|
| 3 | import io.netty.buffer.ByteBuf;
|
| 4 | import io.netty.channel.ChannelHandlerContext;
|
| 5 | import javax.crypto.Cipher;
|
| 6 | import javax.crypto.ShortBufferException;
|
| 7 |
|
| 8 | public class CipherBase {
|
| 9 | private final Cipher cipher;
|
| 10 | private byte[] heapIn = new byte[0];
|
| 11 | private byte[] heapOut = new byte[0];
|
| 12 |
|
| 13 | protected CipherBase(final Cipher cipher) {
|
| 14 | this.cipher = cipher;
|
| 15 | }
|
| 16 |
|
| 17 | private byte[] bufToByte(final ByteBuf in) {
|
| 18 | int readableBytes = in.readableBytes();
|
| 19 | if (this.heapIn.length < readableBytes) {
|
| 20 | this.heapIn = new byte[readableBytes];
|
| 21 | }
|
| 22 |
|
| 23 | in.readBytes(this.heapIn, 0, readableBytes);
|
| 24 | return this.heapIn;
|
| 25 | }
|
| 26 |
|
| 27 | protected ByteBuf decipher(final ChannelHandlerContext ctx, final ByteBuf in) throws ShortBufferException {
|
| 28 | int readableBytes = in.readableBytes();
|
| 29 | byte[] heapIn = this.bufToByte(in);
|
| 30 | ByteBuf heapOut = ctx.alloc().heapBuffer(this.cipher.getOutputSize(readableBytes));
|
| 31 | heapOut.writerIndex(this.cipher.update(heapIn, 0, readableBytes, heapOut.array(), heapOut.arrayOffset()));
|
| 32 | return heapOut;
|
| 33 | }
|
| 34 |
|
| 35 | protected void encipher(final ByteBuf in, final ByteBuf out) throws ShortBufferException {
|
| 36 | int readableBytes = in.readableBytes();
|
| 37 | byte[] heapIn = this.bufToByte(in);
|
| 38 | int outputSize = this.cipher.getOutputSize(readableBytes);
|
| 39 | if (this.heapOut.length < outputSize) {
|
| 40 | this.heapOut = new byte[outputSize];
|
| 41 | }
|
| 42 |
|
| 43 | out.writeBytes(this.heapOut, 0, this.cipher.update(heapIn, 0, readableBytes, this.heapOut));
|
| 44 | }
|
| 45 | }
|
| 46 |
|