0

I'm trying to understand the code that returns the size_in_bytes for a RSA key (I'm looking at PyCryptoDomex). They calculate it:

def size_in_bytes(self):
    return (self.size_in_bits() - 1) // 8 + 1

I would have thought that it would simply be

self.size_in_bits()//8

The specific code is here: github_code_location

I'm sure there's a reason to subtract 1 from the bits and then add 1 to the integer after division but I'd like to understand why.

Tim
  • 1,013
  • 3
  • 17
  • 36

1 Answers1

1
7 // 8 == 0

But you cannot store 7 bits in zero bytes.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • So is it just to protect this single case (size_in_bits=7)? That makes sense, but I would have thought it wouldn't happen in practice. – Tim Jul 25 '20 at 13:12
  • It is not this single case. It is also 6, 5, 4, 3, 2, 1, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49, and that is just a tiny excerpt of the sizes where your approach gives the wrong answer. In fact, your approach gives the wrong answer for *infinitely many* sizes. – Jörg W Mittag Jul 25 '20 at 13:15
  • Of course, the original code assumes that a byte is always 8 bits, which is also wrong. – Jörg W Mittag Jul 25 '20 at 13:16
  • A byte is always 8 bits is python, so the original code is not wrong. – President James K. Polk Jul 26 '20 at 11:15
  • @PresidentJamesK.Polk: I just took a look *again* at the code the OP linked, and I do *not* see any guarantee that `size_in_bits()` is exactly divisible by 8. – Jörg W Mittag Jul 26 '20 at 11:19
  • I agree, but I thought by *...assumes that a byte is always 8 bits...* you were saying something else. – President James K. Polk Jul 26 '20 at 11:25