根据索引

时间:2015-06-01 02:21:56

标签: python python-3.x cryptography byte bytestring

我正在编写一个脚本来打破重复键XOR(Vigenère)密码。

这涉及确定一些数字(0

如果n = 3,则字节[0,2,5,8等]应位于一个块中,字节[1,3,6,9]位于下一个块中,字节[2,4,7,10] ]在最后一个街区。

我可以使用字符串轻松实现这一点,但我不知道如何使用字节对象。我搜索并找到并修改了这段代码:

blocks = [ciphertext[i:i+most_likely_keylength] for i in range(0, len(ciphertext)+1, most_likely_keylength)]

transposedBlocks = list(zip_longest(*blocks, fillvalue=0))

##ciphertext is a bytes object resulting from the following line:
##ciphertext = base64.b64decode(open('Q6.txt', 'r').read())
然而,这会返回一个用整数填充的元组列表,我不知道如何再次“加入”这些整数,所以它们将像以前一样成为长二进制对象。 (这样我就可以在每个元组上运行像Crypto.Util.strxor_c这样的好东西。

对字节对象的'字符串操作'有什么帮助吗?

注意:我正在cryptopals.com上进行Break repeating-key XOR挑战 - 我已经在Github上查看了其他人的解决方案,但他们大多使用专门的加密模块,我希望看到我所知道的内容我在做。

1 个答案:

答案 0 :(得分:1)

从概念上讲,bytes对象整数序列:

>>> tuple(b'ciphertext')
(99, 105, 112, 104, 101, 114, 116, 101, 120, 116)

...所以它的构造函数很乐意接受一个:

>>> bytes((99, 105, 112, 104, 101, 114, 116, 101, 120, 116))
b'ciphertext'

知道了,您可以将第二行更改为:

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0))]

...你会得到bytes个对象:

from itertools import zip_longest

ciphertext = b'ciphertext'
keylength = 3

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext)+1, keylength)]
# [b'cip', b'her', b'tex', b't']

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'chtt', b'iee\x00', b'prx\x00']

但是,您的代码中存在错误 - 因为您在调用len(ciphertext)+1时使用的是len(ciphertext)而不只是range(),因此{{1}中的最后一个空字节字符串如果密文是blocks的完全倍数:

keylength

...这导致ciphertext = b'SplitsEvenly' blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext)+1, keylength)] # [b'Spl', b'its', b'Eve', b'nly', b''] 中所有元素末尾的额外空字节:

transposed

如果删除transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)] # [b'SiEn\x00', b'ptvl\x00', b'lsey\x00'] ,它在两种情况下都能正常工作:

+1
ciphertext = b'ciphertext'

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext), keylength)]
# [b'cip', b'her', b'tex', b't']

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'chtt', b'iee\x00', b'prx\x00']