Xiaomi: fix only short-bytes from int nonce being used during encryption

This commit is contained in:
MrYoranimo 2024-01-05 16:46:21 +01:00 committed by José Rebelo
parent b9cbd14ffe
commit d217a0b15f
3 changed files with 8 additions and 9 deletions

View File

@ -160,12 +160,11 @@ public class XiaomiAuthService extends AbstractXiaomiService {
}
}
public byte[] encrypt(final byte[] arr, final short i) {
public byte[] encrypt(final byte[] arr, final int i) {
final ByteBuffer packetNonce = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN)
.put(encryptionNonce)
.putInt(0)
.putShort(i) // TODO what happens once this overflows?
.putShort((short) 0);
.putInt(i);
try {
return encrypt(encryptionKey, packetNonce.array(), arr);
@ -219,7 +218,7 @@ public class XiaomiAuthService extends AbstractXiaomiService {
.build();
final byte[] encryptedNonces = hmacSHA256(encryptionKey, ArrayUtils.addAll(nonce, watchNonce.getNonce().toByteArray()));
final byte[] encryptedDeviceInfo = encrypt(authDeviceInfo.toByteArray(), (short) 0);
final byte[] encryptedDeviceInfo = encrypt(authDeviceInfo.toByteArray(), 0);
final XiaomiProto.AuthStep3 authStep3 = XiaomiProto.AuthStep3.newBuilder()
.setEncryptedNonces(ByteString.copyFrom(encryptedNonces))
.setEncryptedDeviceInfo(ByteString.copyFrom(encryptedDeviceInfo))

View File

@ -54,7 +54,7 @@ public class XiaomiCharacteristic {
private final XiaomiAuthService authService;
private boolean isEncrypted;
public boolean incrementNonce = true;
private short encryptedIndex = 0;
private int encryptedIndex = 0;
// Chunking
private int numChunks = 0;
@ -311,7 +311,7 @@ public class XiaomiCharacteristic {
// Prepend encrypted index for the nonce
currentPayload.setBytesToSend(
ByteBuffer.allocate(2 + currentPayload.getBytesToSend().length).order(ByteOrder.LITTLE_ENDIAN)
.putShort(encryptedIndex++)
.putShort((short) encryptedIndex++)
.put(currentPayload.getBytesToSend())
.array()
);
@ -344,7 +344,7 @@ public class XiaomiCharacteristic {
buf.put((byte) (encrypt ? 1 : 2));
if (encrypt) {
if (incrementNonce) {
buf.putShort(encryptedIndex++);
buf.putShort((short) encryptedIndex++);
} else {
buf.putShort((short) 0);
}

View File

@ -220,9 +220,9 @@ public class XiaomiSppPacket {
byte[] payload = this.payload;
if (dataType == DATA_TYPE_ENCRYPTED && channel == CHANNEL_PROTO_TX) {
short packetCounter = (short) encryptionCounter.incrementAndGet();
int packetCounter = encryptionCounter.incrementAndGet();
payload = authService.encrypt(payload, packetCounter);
payload = ByteBuffer.allocate(payload.length + 2).order(ByteOrder.LITTLE_ENDIAN).putShort(packetCounter).put(payload).array();
payload = ByteBuffer.allocate(payload.length + 2).order(ByteOrder.LITTLE_ENDIAN).putShort((short) packetCounter).put(payload).array();
} else if (dataType == DATA_TYPE_ENCRYPTED) {
payload = authService.encrypt(payload, (short) 0);
}