-3

好吧,我有一个任务是在 CBC 模式下实现 DES 算法的操作模式:我被困在加密函数的输出给出如下字节的点:b'\xe4\x06-\x95\xf5!P4 '(我正在使用 Crypto.Cipher 的 DES 库)

我不知道该表示是什么或如何将其转换为由零和一组成的二进制字符串,以将其与第二个纯文本进行异或。

任何帮助将不胜感激

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

2 回答 2

1

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

>>> 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'
于 2019-04-27T20:25:12.403 回答
0

你好@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
于 2019-04-26T17:39:37.707 回答