0

I'm pretty new to Python (never coded before in this language) and I need to pass a byte string to a function (as specified here[1]). It receives a string represents a binary number and I want to generate a byte string from it. I've tried countless things but I'm really stuck on how to do it, can you help me please?

I'm trying to pass this value to a library that handles DES, so I don't have any other option than doing it this way.

[1] https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.DES-module.html#new

from Crypto.Cipher import DES

key = "1101101110001000010000000000000100101000010000011000110100010100"

param = key.tobytes() # <-- The function I need

cipher = DES.new(key, DES.MODE_ECB)

simple
  • 53
  • 6

1 Answers1

1

Your key is in its current form a binary Number.

You could get the bytes (still as a string) from that simply with:

length = 8
input_l = [key[i:i+length] for i in range(0,len(key),length)]

And then convert each of these in a list to ints:

input_b = [int(b,base=2) for b in input_l]

The bytearray is then simply given by:

bytearray(input_b)

or

bytes(input_b)

depending on your usecase.


Converting this to a function is left as an exercise to the reader.

elikoga
  • 164
  • 8