无法使用河豚解密

2024-04-29 13:35:58 发布

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

我正在使用Python3和PyCrypto模块实现河豚算法。当我通过命令行给出密钥和明文时,我可以加密,但我无法解密。但是,如果我在Python解释器中使用它,代码就可以正常工作。在

加密(河豚_附件)在

from Crypto.Cipher import Blowfish
from Crypto import Random
from struct import pack
import sys

bs = Blowfish.block_size
key = sys.argv[1].encode()
iv = Random.new().read(bs)
cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)

plaintext = sys.argv[2].encode()
plen = bs - divmod(len(plaintext),bs)[1]
padding = [plen]*plen
padding = pack('b'*plen, *padding)

msg = iv + cipher.encrypt(plaintext + padding)
print(msg)

解密(河豚_递减py)在

^{pr2}$

输出:

$python3 blowfish_encr.py key 'Test it!'

b'\xf8\x1eK)\x81?\xa2\x88\x01\x16\x8e\xdc\xe5\xb9\xd8_K\xce\x03\xe4\x88g\xf8\xa1'

$python3 blowfish_decr.py key '\xf8\x1eK)\x81?\xa2\x88\x01\x16\x8e\xdc\xe5\xb9\xd8_K\xce\x03\xe4\x88g\xf8\xa1'

  File "blowfish_decr.py", line 12, in <module>
   msg = cipher.decrypt(ciphertext)
     File "/usr/lib/python3/dist-packages/Crypto/Cipher/blockalgo.py", line 295, in decrypt
   return self._cipher.decrypt(ciphertext)
  ValueError: Input strings must be a multiple of 8 in length

如何解密?我知道错误是因为当我将编码文本作为字符串输入时,它将所有的\转换为\\,而当我尝试sys.argv[2].encode().replace('\\','\')时,它不起作用,因为\'是{}。在

如何使用命令行参数完成它?在


Tags: keyfrompyimportbssyscryptoencode