0
from Crypto.Cipher import AES
import os
import base64
import socket
import subprocess

BLOCK_SIZE = 16
PADDING='#'

def _pad(data, pad_with=PADDING):
    return data + (BLOCK_SIZE - len(data) % BLOCK_SIZE) * PADDING

I understand that the character "#" is used to pad the block but I can't understand the meaning of the "*", used normally for multiplication.

4 Answers 4

4

In Python, you can multiply a string by an integer to repeat the string that many times. E.g.

'a' * 4

produces

'aaaa'

Any class can overload an operator like * by implementing specially-named methods.

1

str type gets the * operator:

'#' * 10 = '##########'

because __mul__() method is defined in the str class definition:

'#'.__mul__(10) = '##########'
3
  • This doesn't answer the question at all. Commented Mar 17, 2016 at 10:00
  • You're attempting to explain how the * operator maps to the str class' __mul__ method, which is correct, but doesn't answer the OP's question as to what effect it actually has. My answer was simple, yes, but it explains exactly what the OP wanted to know. Commented Mar 17, 2016 at 10:03
  • 1
    Now that you've edited your answer to include an example, it answers the question, and I've removed my down-vote. Commented Mar 17, 2016 at 10:07
1

The * PADDING means exactly that (times PADDING).

* PADDING is add (BLOCK_SIZE - len(data) % BLOCK_SIZE) times # to the end of data.
It calculates the amount of padding needed for the specific data based on its size and the BLOCK_SIZE and adds extra # which is the PADDING.

The calculation is the BLOCK_SIZE minus the length of the data passed to the function, all this modulo the BLOCK_SIZE.

Example:

>>> BLOCK_SIZE = 20
>>> data = 'this is my data'
>>> PADDING = '#'
>>> data + (BLOCK_SIZE - len(data) % BLOCK_SIZE) * PADDING
'this is my data#####'

The calculation performed is:

data + (20 - 15%20)*PADDING = data + (20 - 15)*PADDING = data + 5*PADDING = data + '#####'
-1
>>> a= '#'
>>> a* 12
'############'
>>>
4
  • ok sorry, I was typing this answer meanwhile so many answers came.
    – Rilwan
    Commented Mar 17, 2016 at 10:01
  • That tends to happen with questions like this one. Commented Mar 17, 2016 at 10:05
  • Yes right, also he is newbie. My intention was seeing this simple code he will try in his python console. And next time before asking a question he would try something in his console first.
    – Rilwan
    Commented Mar 17, 2016 at 10:22
  • But your answer included no text. It is not obvious to a newbie that >>> implies the use of thr Python console. Commented Mar 17, 2016 at 10:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.