-3

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 ######
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251

2 Answers2

1

You've accepted an answer, but perhaps you don't realize that byte strings can be XORed as is? No need for conversion to binary. Example:

>>> msg = b'Mark'
>>> key = b'\x01\x02\x03\x04'
>>> enc = bytes([a^b for a,b in zip(msg,key)]) # xor each byte with key byte
>>> enc
b'Lcqo'
>>> dec = bytes([a^b for a,b in zip(enc,key)]) # xor again to decrypt
>>> dec
b'Mark'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

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
vaku
  • 697
  • 8
  • 17
  • thanks alot ! sorry just one more question : plaintext1=bin(int.from_bytes(arr[0].encode(), 'big'))[2:] here the length of the plaintext is 63 bits , how ever arr[0] is 8 bytes , shouldn't it be 64 bits in length ? – nehal abdellatif Apr 26 '19 at 18:00
  • I think because it removes the starting `0`. And if you think my answer above is correct so can you please mark it as accepted...Thanks – vaku Apr 26 '19 at 18:36