Source code for s365b.modules.onedrive.quickxor

"""Microsoft's QuickXorHash, the content hash OneDrive for Business reports.

Byte ``k`` of the content is XORed into a 160-bit value at bit
``(k * 11) % 160``, wrapping around; the length is then XORed into the last
8 bytes. Because the bit position repeats every 160 bytes, the content is
first folded into one 160-byte block (bytes 160 apart XORed together),
which big-integer XOR does at bulk speed; only that block is placed bit by
bit.
"""

from __future__ import annotations

import base64

[docs] WIDTH = 160 # bits
[docs] BLOCK = WIDTH # bytes after which the bit positions repeat
[docs] SHIFT = 11
_MASK = (1 << WIDTH) - 1
[docs] class QuickXorHash: """Incremental QuickXorHash: :meth:`update` with each piece, then :meth:`digest`.""" def __init__(self) -> None: """Start with no content."""
[docs] self.length = 0
self._fold = 0 # 160-byte block, little-endian: byte i holds every byte ≡ i mod 160
[docs] def update(self, data: bytes) -> None: """Add the next piece of content. Args: data: Bytes following those already added. """ if not data: return offset = self.length % BLOCK self.length += len(data) # Pad in front so the piece starts on a block boundary. padded = bytes(offset) + bytes(data) if len(padded) % BLOCK: padded += bytes(BLOCK - len(padded) % BLOCK) n = len(padded) // BLOCK value = int.from_bytes(padded, "little") bits = BLOCK * 8 acc = 0 # Halve the number of blocks each round, XORing the upper half # onto the lower; an odd block out goes straight into acc. while n > 1: if n % 2: n -= 1 acc ^= value >> (n * bits) value &= (1 << (n * bits)) - 1 half = n // 2 value = (value & ((1 << (half * bits)) - 1)) ^ (value >> (half * bits)) n = half self._fold ^= value ^ acc
[docs] def digest(self) -> bytes: """The 20-byte hash of everything added so far. Returns: The hash. """ block = self._fold.to_bytes(BLOCK, "little") result = 0 for i, byte in enumerate(block): if byte: pos = (i * SHIFT) % WIDTH result ^= ((byte << pos) | (byte >> (WIDTH - pos))) & _MASK out = bytearray(result.to_bytes(WIDTH // 8, "little")) for i, b in enumerate(self.length.to_bytes(8, "little")): out[WIDTH // 8 - 8 + i] ^= b return bytes(out)
[docs] def b64digest(self) -> str: """The hash in base64, as Graph gives it (``file.hashes.quickXorHash``). Returns: The hash. """ return base64.b64encode(self.digest()).decode()
[docs] def quick_xor_hash(data: bytes) -> str: """Hash content in one go. Args: data: The content. Returns: The base64 hash. """ h = QuickXorHash() h.update(data) return h.b64digest()