Minestom/src/main/java/net/minestom/server/extras/mojangAuth/CipherBase.java

55 lines
1.8 KiB
Java
Raw Normal View History

package net.minestom.server.extras.mojangAuth;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
2020-11-16 17:02:40 +01:00
import org.jetbrains.annotations.NotNull;
import javax.crypto.Cipher;
import javax.crypto.ShortBufferException;
public class CipherBase {
2020-11-16 17:02:40 +01:00
private final Cipher cipher;
private byte[] inTempArray = new byte[0];
private byte[] outTempArray = new byte[0];
2020-11-16 17:02:40 +01:00
protected CipherBase(@NotNull Cipher cipher) {
this.cipher = cipher;
}
2020-11-16 17:02:40 +01:00
private byte[] bufToByte(ByteBuf buffer) {
int remainingBytes = buffer.readableBytes();
2020-11-16 17:02:40 +01:00
// Need to resize temp array
if (inTempArray.length < remainingBytes) {
inTempArray = new byte[remainingBytes];
}
2020-11-16 17:02:40 +01:00
buffer.readBytes(inTempArray, 0, remainingBytes);
return inTempArray;
}
2020-11-16 17:02:40 +01:00
protected ByteBuf decrypt(ChannelHandlerContext channelHandlerContext, ByteBuf byteBufIn) throws ShortBufferException {
int remainingBytes = byteBufIn.readableBytes();
byte[] bytes = bufToByte(byteBufIn);
2020-11-16 17:02:40 +01:00
ByteBuf outputBuffer = channelHandlerContext.alloc().heapBuffer(cipher.getOutputSize(remainingBytes));
outputBuffer.writerIndex(cipher.update(bytes, 0, remainingBytes, outputBuffer.array(), outputBuffer.arrayOffset()));
2020-11-16 17:02:40 +01:00
return outputBuffer;
}
2020-11-16 17:02:40 +01:00
protected void encrypt(ByteBuf byteBufIn, ByteBuf byteBufOut) throws ShortBufferException {
int remainingBytes = byteBufIn.readableBytes();
byte[] bytes = bufToByte(byteBufIn);
int newSize = cipher.getOutputSize(remainingBytes);
2020-11-16 17:02:40 +01:00
// Need to resize temp array
if (outTempArray.length < newSize) {
outTempArray = new byte[newSize];
}
byteBufOut.writeBytes(outTempArray, 0, cipher.update(bytes, 0, remainingBytes, outTempArray));
}
}