Search code examples
pythonunicodeundefineddespython-cryptography

convert byte like this : (b'\xe4\x06-\x95\xf5!P4' ) to a binary string of zeros and ones in python


well ,i have an assignment to implement the operation modes of the DES algorithm in CBC mode : i am stuck at the point where the output of the encryption function gives bytes like this : b'\xe4\x06-\x95\xf5!P4' (i am using DES library from Crypto.Cipher)

i don't know what is that representation or how to convert it to a binary string of zeros and ones , to xor it with the 2nd plain text.

any help would be highly appreciated

iv = random_iv()


des = DES.new(key)

plaintext1=""
#convert it into binary
plaintext1=bin(int.from_bytes(arr[0].encode(), 'big'))[2:]

y = fn.xor(plaintext1 ,iv)
y1='0'+'b'+y

y= int(y1, 2)
#y is the string output of xoring plaintext1 with the IV 
y= y.to_bytes((y.bit_length() + 7) // 8, 'big').decode()   

encrypted_blocks=[]

# arr is the array of the original blocks of the msg.
for i in range (1, len(arr)):
    c = des.encrypt(y)
    print(c)
    encrypted_blocks.append(c)
    ### stuck here ### 
    #### don't know how to work with c in that format ######

Solution

  • hello @nehal you can convert your bytes into binary by the following method

    # let b is your bytes
    b = b'\xe4\x06-\x95\xf5!P4'
    
    # first convert it to hex
    bHex = b.hex()
    
    # convert it to integet
    bInt = int(bHex, 16)
    
    # finaly convert it to binary
    bBin = "{:08b}".format(bInt)
    
    print(bBin) #1110010000000110001011011001010111110101001000010101000000110100
    

    OR SIMPLY

    b = b'\xe4\x06-\x95\xf5!P4'
    bBin = "{:08b}".format( int( b.hex(), 16 ) )
    print(bBin) #1110010000000110001011011001010111110101001000010101000000110100