像这样转换字节: (b'\xe4\x06-\x95\xf5!P4' ) 到 python 中的零和一的二进制字符串

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

嗯,我有一个任务要实现 DES 算法的操作模式 在 CBC 模式下:我被困在加密函数的输出给出这样的字节的地方:b'\xe4\x06-\x95\xf5!P4' (我正在使用来自 Crypto.Cipher 的 DES 库)

我不知道那个表示是什么,也不知道如何将它转换为由 0 和 1 组成的二进制字符串,以便与第二个纯文本进行异或运算。

任何帮助将不胜感激

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 ######

你好@nehal 你可以通过以下方法将你的字节转换成二进制

# 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

或简单地

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

您已经接受了一个答案,但也许您没有意识到字节串可以按原样进行异或运算?无需转换为二进制。示例:

>>> 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'