我正在使用Python3和PyCrypto模块进行Blowfish算法。当我通过命令行提供密钥和明文但我无法解密时,我能够加密。但是,如果我在Python Interpreter中使用它,代码就能正常工作。
ENCRYPTION(blowfish_encr.py)
ORDER BY
DECRYPTION(blowfish_decr.py)
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)
输出:
$ python3 blowfish_encr.py key'Test it!'
from Crypto.Cipher import Blowfish
from struct import pack
import sys
bs = Blowfish.block_size
ciphertext = sys.argv[2].encode()
key = sys.argv[1].encode()
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))
$ python3 blowfish_decr.py key'\ xf8 \ x1eK)\ x81?\ xa2 \ x88 \ x01 \ x16 \ x8e \ xdc \ xe5 \ xb9 \ xd8_K \ xce \ x03 \ xe4 \ x88g \ xf8 \ xa1'< / p>
b'\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
转换为\
,当我尝试\\
时,它不起作用,因为{{1是} sys.argv[2].encode().replace('\\','\')
。
如何使用命令行参数完成它?