使用ECB函数进行CBC解密

时间:2017-02-17 07:45:14

标签: python cryptography pycrypto cbc-mode

尝试解决Cryptopals Challenge 10,其中CBC使用所有ASCII 0(\ x00 \ x00 \ x00& c)的IV对“黄色潜水艇”解密文本文件。 链接到文本文件如下:

http://cryptopals.com/static/challenge-data/10.txt

我已经遵循CBC使用的算法,采用密文,解密(使用ECB解密),然后将xor与初始化向量用于第一个块,密文(i-1)用于后续块。然而,由于一些不可理解的原因,我没有得到可读的解密。我在解密后打印时只看到一些奇怪的字符:

from Crypto.Cipher import AES
key ='YELLOW SUBMARINE'
iv = "%00%00%00"*32
iv = iv.replace('%',r'\x')

#XOR-ing function
def xor_strings(a, b):
    return "".join(chr(ord(a1) ^ ord(b1)) for a1, b1 in zip(a, b))

#Taking input file and converting it into a single string 
file = open('10.txt','r')
data = file.read()
block = 128

obj = AES.new(key, AES.MODE_ECB)

def split_len(string, size):
    return [string[i:i+size] for i in range(0, len(string), size)]

mylist = split_len(data,block)


decrypted = ""
for i in range (0,len(mylist)):
     mystr = obj.decrypt(mylist[i])
     if (i==0):
          decrypted = decrypted + xor_strings(mystr,iv)
     else:
          decrypted = decrypted + xor_strings(mystr, mylist[i-1])
 print decrypted

这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

iv需要16个零字节(这个问题在说“ASCII 0”时没有明确的措辞):

iv = "\x00" * 16

在解密文件之前,您需要对文件进行base64解码:

from base64 import b64decode
#...

file = open('10.txt','r')
data = file.read()
data = b64decode(data)

最后,您的块大小需要以字节为单位才能使此代码起作用,而不是位:

block = 16