emulbreh/pyffx

counter i is reset to 0 for each round

Opened this issue · 2 comments

i = 0

In reading the accompanying doc on this: https://medium.com/asecuritysite-when-bob-met-alice/ffx-schemes-for-format-preserving-encryption-a2a7aa4f1377 I noticed that the counter is reset each round. Works fine removing the initialization and allows the value to be carried.

I agree that reusing the variable like that is ugly. The round number i is still used to salt the hash though: it's packed into key before i is reset.
If we wouldn't include the round number directly and instead just used it as an offset for i all rounds would end up using the same sequence, just shifted by the round number.

Thanks for bringing the post to my attention, I hadn't seen that before!

In my testing it is not incremented in the generator and is set to 0 each round. The way I see the code, i is set in the encrypt function using the range of self.rounds:

        a, b = self.split(v)
        for i in range(self.rounds):
            c = self.add(radix, a, self.round(radix, i, b))
            a, b = b, c
        return a + b

In this way, i is incrementing already and there doesn't seem to be a reason to attempt to increment again.

To test, I simply put a print(i) in the round function:

        key = struct.pack('I%sI' % len(s), i, *s)
        chars_per_hash = int(self.digest_size * math.log(256, radix))
        i = 0
        while True:
            print(i)
            h = hmac.new(self.key, key + struct.pack('I', i), self.digestmod)
            d = int(h.hexdigest(), 16)
            for _ in range(chars_per_hash):
                d, r = divmod(d, radix)
                yield r
            key = h.digest()
            i += 1

However, if you want to keep the increment inside round, you just have to move the i += 1 to inside the for loop (this brings up that the assignment of key should also be moved if that is indeed needed):

        key = struct.pack('I%sI' % len(s), i, *s)
        chars_per_hash = int(self.digest_size * math.log(256, radix))
        i = 0
        while True:
            print(i)
            h = hmac.new(self.key, key + struct.pack('I', i), self.digestmod)
            d = int(h.hexdigest(), 16)
            for _ in range(chars_per_hash):
                d, r = divmod(d, radix)
                yield r
                i += 1
            key = h.digest()