use of sugar.free.sightparser.error.UnknownAuthMessageError in project SightRemote by TebbeUbben.
the class AuthLayerMessage method deserialize.
public static AuthLayerMessage deserialize(ByteBuf data, BigInteger lastNonce, byte[] key) throws IllegalAccessException, InstantiationException, SightError {
// Preamble
data.shift(4);
int packetLength = data.readUInt16LE();
// Packet length XOR
data.shift(2);
byte[] crcContent = data.getBytes(packetLength - 10);
byte[] header = data.getBytes(21);
byte version = data.readByte();
byte command = data.readByte();
Class clazz = MESSAGES.get(command);
if (clazz == null)
throw new UnknownAuthMessageError(command);
int dataLength = data.readUInt16LE();
long commID = data.readUInt32LE();
byte[] nonceTrailer = data.getBytes(13);
byte[] nonce = data.readBytesLE(13);
byte[] payload = data.readBytes(dataLength);
byte[] trailer = data.readBytes(8);
boolean crcPacket = CRCAuthLayerMessage.class.isAssignableFrom(clazz);
BigInteger nonceInt = new BigInteger(nonce);
if (version != VERSION) {
throw new InvalidAuthVersionError(version, VERSION);
} else if (lastNonce != null && lastNonce.equals(BigInteger.ZERO) && nonceInt.compareTo(lastNonce) != 1) {
throw new InvalidNonceError(nonce, processNonce(lastNonce.add(BigInteger.ONE)));
} else {
if (crcPacket) {
byte[] crcBytes = new byte[2];
byte[] rawData = new byte[dataLength - 2];
System.arraycopy(payload, dataLength - 2, crcBytes, 0, 2);
System.arraycopy(payload, 0, rawData, 0, dataLength - 2);
payload = rawData;
int crc = (crcBytes[0] & 0xFF | (crcBytes[1] & 0xFF) << 8);
int calculatedCRC = Cryptograph.calculateCRC(crcContent);
if (crc != calculatedCRC)
throw new InvalidAuthCRCError(crc, calculatedCRC);
} else {
payload = Cryptograph.encryptDataCTR(payload, key, nonceTrailer);
byte[] calculatedTrailer = Cryptograph.produceCCMTag(nonceTrailer, payload, header, key);
if (!Arrays.equals(trailer, calculatedTrailer))
throw new InvalidTrailerError(trailer, calculatedTrailer);
}
AuthLayerMessage message = (AuthLayerMessage) clazz.newInstance();
message.nonce = nonceInt;
message.commID = commID;
ByteBuf byteBuf = new ByteBuf(payload.length);
byteBuf.putBytes(payload);
message.parse(byteBuf);
return message;
}
}
Aggregations