如何在Pycrypto中使用Blowfish解密?

2024-04-29 12:27:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了一个加密数据的例子,但是我找不到任何关于如何解密的例子。

加密示例:

>>> from Crypto.Cipher import Blowfish
>>> from Crypto import Random
>>> from struct import pack
>>>
>>> bs = Blowfish.block_size
>>> key = b'An arbitrarily long key'
>>> iv = Random.new().read(bs)
>>> cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
>>> plaintext = b'docendo discimus '
>>> plen = bs - divmod(len(plaintext),bs)[1]
>>> padding = [plen]*plen
>>> padding = pack('b'*plen, *padding)
>>> msg = iv + cipher.encrypt(plaintext + padding)

我没有找到任何关于如何解密的例子。


Tags: keyfromimportnewbsrandomcryptopack
1条回答
网友
1楼 · 发布于 2024-04-29 12:27:33

我们来观察一下:

  • CBC模式需要与块大小具有相同长度的初始化向量(IV)
  • 纯文本是包含padding的实际消息(PKCS#5 padding in RFC 2898 Sec. 6.1.1 Step 4
  • IV是密文的前置

需要做什么:

  • 使用同一个键
  • 在创建解密程序之前阅读IV
  • 通过查看最后一个字节来删除解密后的填充,将其计算为整数,并从明文结尾删除尽可能多的字节

代码:

from Crypto.Cipher import Blowfish
from struct import pack

bs = Blowfish.block_size
key = b'An arbitrarily long key'
ciphertext = b'\xe2:\x141vp\x05\x92\xd7\xfa\xb5@\xda\x05w.\xaaRG+U+\xc5G\x08\xdf\xf4Xua\x88\x1b'
iv = ciphertext[:bs]
ciphertext = ciphertext[bs:]

cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
msg = cipher.decrypt(ciphertext)

last_byte = msg[-1]
msg = msg[:- (last_byte if type(last_byte) is int else ord(last_byte))]
print(repr(msg))

相关问题 更多 >